[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Sema / SemaLookup.cpp
blob70a32bd737160caf02981bfa21e29db8c3911efc
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/ErrorHandling.h"
44 #include <algorithm>
45 #include <iterator>
46 #include <list>
47 #include <set>
48 #include <utility>
49 #include <vector>
51 #include "OpenCLBuiltins.inc"
53 using namespace clang;
54 using namespace sema;
56 namespace {
57 class UnqualUsingEntry {
58 const DeclContext *Nominated;
59 const DeclContext *CommonAncestor;
61 public:
62 UnqualUsingEntry(const DeclContext *Nominated,
63 const DeclContext *CommonAncestor)
64 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
67 const DeclContext *getCommonAncestor() const {
68 return CommonAncestor;
71 const DeclContext *getNominatedNamespace() const {
72 return Nominated;
75 // Sort by the pointer value of the common ancestor.
76 struct Comparator {
77 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
78 return L.getCommonAncestor() < R.getCommonAncestor();
81 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
82 return E.getCommonAncestor() < DC;
85 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
86 return DC < E.getCommonAncestor();
91 /// A collection of using directives, as used by C++ unqualified
92 /// lookup.
93 class UnqualUsingDirectiveSet {
94 Sema &SemaRef;
96 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
98 ListTy list;
99 llvm::SmallPtrSet<DeclContext*, 8> visited;
101 public:
102 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
104 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
105 // C++ [namespace.udir]p1:
106 // During unqualified name lookup, the names appear as if they
107 // were declared in the nearest enclosing namespace which contains
108 // both the using-directive and the nominated namespace.
109 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
110 assert(InnermostFileDC && InnermostFileDC->isFileContext());
112 for (; S; S = S->getParent()) {
113 // C++ [namespace.udir]p1:
114 // A using-directive shall not appear in class scope, but may
115 // appear in namespace scope or in block scope.
116 DeclContext *Ctx = S->getEntity();
117 if (Ctx && Ctx->isFileContext()) {
118 visit(Ctx, Ctx);
119 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
120 for (auto *I : S->using_directives())
121 if (SemaRef.isVisible(I))
122 visit(I, InnermostFileDC);
127 // Visits a context and collect all of its using directives
128 // recursively. Treats all using directives as if they were
129 // declared in the context.
131 // A given context is only every visited once, so it is important
132 // that contexts be visited from the inside out in order to get
133 // the effective DCs right.
134 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
135 if (!visited.insert(DC).second)
136 return;
138 addUsingDirectives(DC, EffectiveDC);
141 // Visits a using directive and collects all of its using
142 // directives recursively. Treats all using directives as if they
143 // were declared in the effective DC.
144 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
145 DeclContext *NS = UD->getNominatedNamespace();
146 if (!visited.insert(NS).second)
147 return;
149 addUsingDirective(UD, EffectiveDC);
150 addUsingDirectives(NS, EffectiveDC);
153 // Adds all the using directives in a context (and those nominated
154 // by its using directives, transitively) as if they appeared in
155 // the given effective context.
156 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
157 SmallVector<DeclContext*, 4> queue;
158 while (true) {
159 for (auto *UD : DC->using_directives()) {
160 DeclContext *NS = UD->getNominatedNamespace();
161 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
162 addUsingDirective(UD, EffectiveDC);
163 queue.push_back(NS);
167 if (queue.empty())
168 return;
170 DC = queue.pop_back_val();
174 // Add a using directive as if it had been declared in the given
175 // context. This helps implement C++ [namespace.udir]p3:
176 // The using-directive is transitive: if a scope contains a
177 // using-directive that nominates a second namespace that itself
178 // contains using-directives, the effect is as if the
179 // using-directives from the second namespace also appeared in
180 // the first.
181 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
182 // Find the common ancestor between the effective context and
183 // the nominated namespace.
184 DeclContext *Common = UD->getNominatedNamespace();
185 while (!Common->Encloses(EffectiveDC))
186 Common = Common->getParent();
187 Common = Common->getPrimaryContext();
189 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
192 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
194 typedef ListTy::const_iterator const_iterator;
196 const_iterator begin() const { return list.begin(); }
197 const_iterator end() const { return list.end(); }
199 llvm::iterator_range<const_iterator>
200 getNamespacesFor(DeclContext *DC) const {
201 return llvm::make_range(std::equal_range(begin(), end(),
202 DC->getPrimaryContext(),
203 UnqualUsingEntry::Comparator()));
206 } // end anonymous namespace
208 // Retrieve the set of identifier namespaces that correspond to a
209 // specific kind of name lookup.
210 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
211 bool CPlusPlus,
212 bool Redeclaration) {
213 unsigned IDNS = 0;
214 switch (NameKind) {
215 case Sema::LookupObjCImplicitSelfParam:
216 case Sema::LookupOrdinaryName:
217 case Sema::LookupRedeclarationWithLinkage:
218 case Sema::LookupLocalFriendName:
219 case Sema::LookupDestructorName:
220 IDNS = Decl::IDNS_Ordinary;
221 if (CPlusPlus) {
222 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
223 if (Redeclaration)
224 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
226 if (Redeclaration)
227 IDNS |= Decl::IDNS_LocalExtern;
228 break;
230 case Sema::LookupOperatorName:
231 // Operator lookup is its own crazy thing; it is not the same
232 // as (e.g.) looking up an operator name for redeclaration.
233 assert(!Redeclaration && "cannot do redeclaration operator lookup");
234 IDNS = Decl::IDNS_NonMemberOperator;
235 break;
237 case Sema::LookupTagName:
238 if (CPlusPlus) {
239 IDNS = Decl::IDNS_Type;
241 // When looking for a redeclaration of a tag name, we add:
242 // 1) TagFriend to find undeclared friend decls
243 // 2) Namespace because they can't "overload" with tag decls.
244 // 3) Tag because it includes class templates, which can't
245 // "overload" with tag decls.
246 if (Redeclaration)
247 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
248 } else {
249 IDNS = Decl::IDNS_Tag;
251 break;
253 case Sema::LookupLabel:
254 IDNS = Decl::IDNS_Label;
255 break;
257 case Sema::LookupMemberName:
258 IDNS = Decl::IDNS_Member;
259 if (CPlusPlus)
260 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
261 break;
263 case Sema::LookupNestedNameSpecifierName:
264 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
265 break;
267 case Sema::LookupNamespaceName:
268 IDNS = Decl::IDNS_Namespace;
269 break;
271 case Sema::LookupUsingDeclName:
272 assert(Redeclaration && "should only be used for redecl lookup");
273 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
274 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
275 Decl::IDNS_LocalExtern;
276 break;
278 case Sema::LookupObjCProtocolName:
279 IDNS = Decl::IDNS_ObjCProtocol;
280 break;
282 case Sema::LookupOMPReductionName:
283 IDNS = Decl::IDNS_OMPReduction;
284 break;
286 case Sema::LookupOMPMapperName:
287 IDNS = Decl::IDNS_OMPMapper;
288 break;
290 case Sema::LookupAnyName:
291 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
292 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
293 | Decl::IDNS_Type;
294 break;
296 return IDNS;
299 void LookupResult::configure() {
300 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
301 isForRedeclaration());
303 // If we're looking for one of the allocation or deallocation
304 // operators, make sure that the implicitly-declared new and delete
305 // operators can be found.
306 switch (NameInfo.getName().getCXXOverloadedOperator()) {
307 case OO_New:
308 case OO_Delete:
309 case OO_Array_New:
310 case OO_Array_Delete:
311 getSema().DeclareGlobalNewDelete();
312 break;
314 default:
315 break;
318 // Compiler builtins are always visible, regardless of where they end
319 // up being declared.
320 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
321 if (unsigned BuiltinID = Id->getBuiltinID()) {
322 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
323 AllowHidden = true;
328 bool LookupResult::checkDebugAssumptions() const {
329 // This function is never called by NDEBUG builds.
330 assert(ResultKind != NotFound || Decls.size() == 0);
331 assert(ResultKind != Found || Decls.size() == 1);
332 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
333 (Decls.size() == 1 &&
334 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
335 assert(ResultKind != FoundUnresolvedValue || checkUnresolved());
336 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
337 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
338 Ambiguity == AmbiguousBaseSubobjectTypes)));
339 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
340 (Ambiguity == AmbiguousBaseSubobjectTypes ||
341 Ambiguity == AmbiguousBaseSubobjects)));
342 return true;
345 // Necessary because CXXBasePaths is not complete in Sema.h
346 void LookupResult::deletePaths(CXXBasePaths *Paths) {
347 delete Paths;
350 /// Get a representative context for a declaration such that two declarations
351 /// will have the same context if they were found within the same scope.
352 static DeclContext *getContextForScopeMatching(Decl *D) {
353 // For function-local declarations, use that function as the context. This
354 // doesn't account for scopes within the function; the caller must deal with
355 // those.
356 DeclContext *DC = D->getLexicalDeclContext();
357 if (DC->isFunctionOrMethod())
358 return DC;
360 // Otherwise, look at the semantic context of the declaration. The
361 // declaration must have been found there.
362 return D->getDeclContext()->getRedeclContext();
365 /// Determine whether \p D is a better lookup result than \p Existing,
366 /// given that they declare the same entity.
367 static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
368 NamedDecl *D, NamedDecl *Existing) {
369 // When looking up redeclarations of a using declaration, prefer a using
370 // shadow declaration over any other declaration of the same entity.
371 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
372 !isa<UsingShadowDecl>(Existing))
373 return true;
375 auto *DUnderlying = D->getUnderlyingDecl();
376 auto *EUnderlying = Existing->getUnderlyingDecl();
378 // If they have different underlying declarations, prefer a typedef over the
379 // original type (this happens when two type declarations denote the same
380 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
381 // might carry additional semantic information, such as an alignment override.
382 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
383 // declaration over a typedef. Also prefer a tag over a typedef for
384 // destructor name lookup because in some contexts we only accept a
385 // class-name in a destructor declaration.
386 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
387 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
388 bool HaveTag = isa<TagDecl>(EUnderlying);
389 bool WantTag =
390 Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName;
391 return HaveTag != WantTag;
394 // Pick the function with more default arguments.
395 // FIXME: In the presence of ambiguous default arguments, we should keep both,
396 // so we can diagnose the ambiguity if the default argument is needed.
397 // See C++ [over.match.best]p3.
398 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
399 auto *EFD = cast<FunctionDecl>(EUnderlying);
400 unsigned DMin = DFD->getMinRequiredArguments();
401 unsigned EMin = EFD->getMinRequiredArguments();
402 // If D has more default arguments, it is preferred.
403 if (DMin != EMin)
404 return DMin < EMin;
405 // FIXME: When we track visibility for default function arguments, check
406 // that we pick the declaration with more visible default arguments.
409 // Pick the template with more default template arguments.
410 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
411 auto *ETD = cast<TemplateDecl>(EUnderlying);
412 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
413 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
414 // If D has more default arguments, it is preferred. Note that default
415 // arguments (and their visibility) is monotonically increasing across the
416 // redeclaration chain, so this is a quick proxy for "is more recent".
417 if (DMin != EMin)
418 return DMin < EMin;
419 // If D has more *visible* default arguments, it is preferred. Note, an
420 // earlier default argument being visible does not imply that a later
421 // default argument is visible, so we can't just check the first one.
422 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
423 I != N; ++I) {
424 if (!S.hasVisibleDefaultArgument(
425 ETD->getTemplateParameters()->getParam(I)) &&
426 S.hasVisibleDefaultArgument(
427 DTD->getTemplateParameters()->getParam(I)))
428 return true;
432 // VarDecl can have incomplete array types, prefer the one with more complete
433 // array type.
434 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
435 VarDecl *EVD = cast<VarDecl>(EUnderlying);
436 if (EVD->getType()->isIncompleteType() &&
437 !DVD->getType()->isIncompleteType()) {
438 // Prefer the decl with a more complete type if visible.
439 return S.isVisible(DVD);
441 return false; // Avoid picking up a newer decl, just because it was newer.
444 // For most kinds of declaration, it doesn't really matter which one we pick.
445 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
446 // If the existing declaration is hidden, prefer the new one. Otherwise,
447 // keep what we've got.
448 return !S.isVisible(Existing);
451 // Pick the newer declaration; it might have a more precise type.
452 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
453 Prev = Prev->getPreviousDecl())
454 if (Prev == EUnderlying)
455 return true;
456 return false;
459 /// Determine whether \p D can hide a tag declaration.
460 static bool canHideTag(NamedDecl *D) {
461 // C++ [basic.scope.declarative]p4:
462 // Given a set of declarations in a single declarative region [...]
463 // exactly one declaration shall declare a class name or enumeration name
464 // that is not a typedef name and the other declarations shall all refer to
465 // the same variable, non-static data member, or enumerator, or all refer
466 // to functions and function templates; in this case the class name or
467 // enumeration name is hidden.
468 // C++ [basic.scope.hiding]p2:
469 // A class name or enumeration name can be hidden by the name of a
470 // variable, data member, function, or enumerator declared in the same
471 // scope.
472 // An UnresolvedUsingValueDecl always instantiates to one of these.
473 D = D->getUnderlyingDecl();
474 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
475 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
476 isa<UnresolvedUsingValueDecl>(D);
479 /// Resolves the result kind of this lookup.
480 void LookupResult::resolveKind() {
481 unsigned N = Decls.size();
483 // Fast case: no possible ambiguity.
484 if (N == 0) {
485 assert(ResultKind == NotFound ||
486 ResultKind == NotFoundInCurrentInstantiation);
487 return;
490 // If there's a single decl, we need to examine it to decide what
491 // kind of lookup this is.
492 if (N == 1) {
493 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
494 if (isa<FunctionTemplateDecl>(D))
495 ResultKind = FoundOverloaded;
496 else if (isa<UnresolvedUsingValueDecl>(D))
497 ResultKind = FoundUnresolvedValue;
498 return;
501 // Don't do any extra resolution if we've already resolved as ambiguous.
502 if (ResultKind == Ambiguous) return;
504 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
505 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
507 bool Ambiguous = false;
508 bool HasTag = false, HasFunction = false;
509 bool HasFunctionTemplate = false, HasUnresolved = false;
510 NamedDecl *HasNonFunction = nullptr;
512 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
514 unsigned UniqueTagIndex = 0;
516 unsigned I = 0;
517 while (I < N) {
518 NamedDecl *D = Decls[I]->getUnderlyingDecl();
519 D = cast<NamedDecl>(D->getCanonicalDecl());
521 // Ignore an invalid declaration unless it's the only one left.
522 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
523 Decls[I] = Decls[--N];
524 continue;
527 llvm::Optional<unsigned> ExistingI;
529 // Redeclarations of types via typedef can occur both within a scope
530 // and, through using declarations and directives, across scopes. There is
531 // no ambiguity if they all refer to the same type, so unique based on the
532 // canonical type.
533 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
534 QualType T = getSema().Context.getTypeDeclType(TD);
535 auto UniqueResult = UniqueTypes.insert(
536 std::make_pair(getSema().Context.getCanonicalType(T), I));
537 if (!UniqueResult.second) {
538 // The type is not unique.
539 ExistingI = UniqueResult.first->second;
543 // For non-type declarations, check for a prior lookup result naming this
544 // canonical declaration.
545 if (!ExistingI) {
546 auto UniqueResult = Unique.insert(std::make_pair(D, I));
547 if (!UniqueResult.second) {
548 // We've seen this entity before.
549 ExistingI = UniqueResult.first->second;
553 if (ExistingI) {
554 // This is not a unique lookup result. Pick one of the results and
555 // discard the other.
556 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
557 Decls[*ExistingI]))
558 Decls[*ExistingI] = Decls[I];
559 Decls[I] = Decls[--N];
560 continue;
563 // Otherwise, do some decl type analysis and then continue.
565 if (isa<UnresolvedUsingValueDecl>(D)) {
566 HasUnresolved = true;
567 } else if (isa<TagDecl>(D)) {
568 if (HasTag)
569 Ambiguous = true;
570 UniqueTagIndex = I;
571 HasTag = true;
572 } else if (isa<FunctionTemplateDecl>(D)) {
573 HasFunction = true;
574 HasFunctionTemplate = true;
575 } else if (isa<FunctionDecl>(D)) {
576 HasFunction = true;
577 } else {
578 if (HasNonFunction) {
579 // If we're about to create an ambiguity between two declarations that
580 // are equivalent, but one is an internal linkage declaration from one
581 // module and the other is an internal linkage declaration from another
582 // module, just skip it.
583 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
584 D)) {
585 EquivalentNonFunctions.push_back(D);
586 Decls[I] = Decls[--N];
587 continue;
590 Ambiguous = true;
592 HasNonFunction = D;
594 I++;
597 // C++ [basic.scope.hiding]p2:
598 // A class name or enumeration name can be hidden by the name of
599 // an object, function, or enumerator declared in the same
600 // scope. If a class or enumeration name and an object, function,
601 // or enumerator are declared in the same scope (in any order)
602 // with the same name, the class or enumeration name is hidden
603 // wherever the object, function, or enumerator name is visible.
604 // But it's still an error if there are distinct tag types found,
605 // even if they're not visible. (ref?)
606 if (N > 1 && HideTags && HasTag && !Ambiguous &&
607 (HasFunction || HasNonFunction || HasUnresolved)) {
608 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
609 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
610 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
611 getContextForScopeMatching(OtherDecl)) &&
612 canHideTag(OtherDecl))
613 Decls[UniqueTagIndex] = Decls[--N];
614 else
615 Ambiguous = true;
618 // FIXME: This diagnostic should really be delayed until we're done with
619 // the lookup result, in case the ambiguity is resolved by the caller.
620 if (!EquivalentNonFunctions.empty() && !Ambiguous)
621 getSema().diagnoseEquivalentInternalLinkageDeclarations(
622 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
624 Decls.truncate(N);
626 if (HasNonFunction && (HasFunction || HasUnresolved))
627 Ambiguous = true;
629 if (Ambiguous)
630 setAmbiguous(LookupResult::AmbiguousReference);
631 else if (HasUnresolved)
632 ResultKind = LookupResult::FoundUnresolvedValue;
633 else if (N > 1 || HasFunctionTemplate)
634 ResultKind = LookupResult::FoundOverloaded;
635 else
636 ResultKind = LookupResult::Found;
639 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
640 CXXBasePaths::const_paths_iterator I, E;
641 for (I = P.begin(), E = P.end(); I != E; ++I)
642 for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;
643 ++DI)
644 addDecl(*DI);
647 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
648 Paths = new CXXBasePaths;
649 Paths->swap(P);
650 addDeclsFromBasePaths(*Paths);
651 resolveKind();
652 setAmbiguous(AmbiguousBaseSubobjects);
655 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
656 Paths = new CXXBasePaths;
657 Paths->swap(P);
658 addDeclsFromBasePaths(*Paths);
659 resolveKind();
660 setAmbiguous(AmbiguousBaseSubobjectTypes);
663 void LookupResult::print(raw_ostream &Out) {
664 Out << Decls.size() << " result(s)";
665 if (isAmbiguous()) Out << ", ambiguous";
666 if (Paths) Out << ", base paths present";
668 for (iterator I = begin(), E = end(); I != E; ++I) {
669 Out << "\n";
670 (*I)->print(Out, 2);
674 LLVM_DUMP_METHOD void LookupResult::dump() {
675 llvm::errs() << "lookup results for " << getLookupName().getAsString()
676 << ":\n";
677 for (NamedDecl *D : *this)
678 D->dump();
681 /// Diagnose a missing builtin type.
682 static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,
683 llvm::StringRef Name) {
684 S.Diag(SourceLocation(), diag::err_opencl_type_not_found)
685 << TypeClass << Name;
686 return S.Context.VoidTy;
689 /// Lookup an OpenCL enum type.
690 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
691 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
692 Sema::LookupTagName);
693 S.LookupName(Result, S.TUScope);
694 if (Result.empty())
695 return diagOpenCLBuiltinTypeError(S, "enum", Name);
696 EnumDecl *Decl = Result.getAsSingle<EnumDecl>();
697 if (!Decl)
698 return diagOpenCLBuiltinTypeError(S, "enum", Name);
699 return S.Context.getEnumType(Decl);
702 /// Lookup an OpenCL typedef type.
703 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
704 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
705 Sema::LookupOrdinaryName);
706 S.LookupName(Result, S.TUScope);
707 if (Result.empty())
708 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
709 TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();
710 if (!Decl)
711 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
712 return S.Context.getTypedefType(Decl);
715 /// Get the QualType instances of the return type and arguments for an OpenCL
716 /// builtin function signature.
717 /// \param S (in) The Sema instance.
718 /// \param OpenCLBuiltin (in) The signature currently handled.
719 /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
720 /// type used as return type or as argument.
721 /// Only meaningful for generic types, otherwise equals 1.
722 /// \param RetTypes (out) List of the possible return types.
723 /// \param ArgTypes (out) List of the possible argument types. For each
724 /// argument, ArgTypes contains QualTypes for the Cartesian product
725 /// of (vector sizes) x (types) .
726 static void GetQualTypesForOpenCLBuiltin(
727 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,
728 SmallVector<QualType, 1> &RetTypes,
729 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
730 // Get the QualType instances of the return types.
731 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];
732 OCL2Qual(S, TypeTable[Sig], RetTypes);
733 GenTypeMaxCnt = RetTypes.size();
735 // Get the QualType instances of the arguments.
736 // First type is the return type, skip it.
737 for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) {
738 SmallVector<QualType, 1> Ty;
739 OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
740 Ty);
741 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
742 ArgTypes.push_back(std::move(Ty));
746 /// Create a list of the candidate function overloads for an OpenCL builtin
747 /// function.
748 /// \param Context (in) The ASTContext instance.
749 /// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic
750 /// type used as return type or as argument.
751 /// Only meaningful for generic types, otherwise equals 1.
752 /// \param FunctionList (out) List of FunctionTypes.
753 /// \param RetTypes (in) List of the possible return types.
754 /// \param ArgTypes (in) List of the possible types for the arguments.
755 static void GetOpenCLBuiltinFctOverloads(
756 ASTContext &Context, unsigned GenTypeMaxCnt,
757 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,
758 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
759 FunctionProtoType::ExtProtoInfo PI(
760 Context.getDefaultCallingConvention(false, false, true));
761 PI.Variadic = false;
763 // Do not attempt to create any FunctionTypes if there are no return types,
764 // which happens when a type belongs to a disabled extension.
765 if (RetTypes.size() == 0)
766 return;
768 // Create FunctionTypes for each (gen)type.
769 for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
770 SmallVector<QualType, 5> ArgList;
772 for (unsigned A = 0; A < ArgTypes.size(); A++) {
773 // Bail out if there is an argument that has no available types.
774 if (ArgTypes[A].size() == 0)
775 return;
777 // Builtins such as "max" have an "sgentype" argument that represents
778 // the corresponding scalar type of a gentype. The number of gentypes
779 // must be a multiple of the number of sgentypes.
780 assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 &&
781 "argument type count not compatible with gentype type count");
782 unsigned Idx = IGenType % ArgTypes[A].size();
783 ArgList.push_back(ArgTypes[A][Idx]);
786 FunctionList.push_back(Context.getFunctionType(
787 RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI));
791 /// When trying to resolve a function name, if isOpenCLBuiltin() returns a
792 /// non-null <Index, Len> pair, then the name is referencing an OpenCL
793 /// builtin function. Add all candidate signatures to the LookUpResult.
795 /// \param S (in) The Sema instance.
796 /// \param LR (inout) The LookupResult instance.
797 /// \param II (in) The identifier being resolved.
798 /// \param FctIndex (in) Starting index in the BuiltinTable.
799 /// \param Len (in) The signature list has Len elements.
800 static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR,
801 IdentifierInfo *II,
802 const unsigned FctIndex,
803 const unsigned Len) {
804 // The builtin function declaration uses generic types (gentype).
805 bool HasGenType = false;
807 // Maximum number of types contained in a generic type used as return type or
808 // as argument. Only meaningful for generic types, otherwise equals 1.
809 unsigned GenTypeMaxCnt;
811 ASTContext &Context = S.Context;
813 for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {
814 const OpenCLBuiltinStruct &OpenCLBuiltin =
815 BuiltinTable[FctIndex + SignatureIndex];
817 // Ignore this builtin function if it is not available in the currently
818 // selected language version.
819 if (!isOpenCLVersionContainedInMask(Context.getLangOpts(),
820 OpenCLBuiltin.Versions))
821 continue;
823 // Ignore this builtin function if it carries an extension macro that is
824 // not defined. This indicates that the extension is not supported by the
825 // target, so the builtin function should not be available.
826 StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];
827 if (!Extensions.empty()) {
828 SmallVector<StringRef, 2> ExtVec;
829 Extensions.split(ExtVec, " ");
830 bool AllExtensionsDefined = true;
831 for (StringRef Ext : ExtVec) {
832 if (!S.getPreprocessor().isMacroDefined(Ext)) {
833 AllExtensionsDefined = false;
834 break;
837 if (!AllExtensionsDefined)
838 continue;
841 SmallVector<QualType, 1> RetTypes;
842 SmallVector<SmallVector<QualType, 1>, 5> ArgTypes;
844 // Obtain QualType lists for the function signature.
845 GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,
846 ArgTypes);
847 if (GenTypeMaxCnt > 1) {
848 HasGenType = true;
851 // Create function overload for each type combination.
852 std::vector<QualType> FunctionList;
853 GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,
854 ArgTypes);
856 SourceLocation Loc = LR.getNameLoc();
857 DeclContext *Parent = Context.getTranslationUnitDecl();
858 FunctionDecl *NewOpenCLBuiltin;
860 for (const auto &FTy : FunctionList) {
861 NewOpenCLBuiltin = FunctionDecl::Create(
862 Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,
863 S.getCurFPFeatures().isFPConstrained(), false,
864 FTy->isFunctionProtoType());
865 NewOpenCLBuiltin->setImplicit();
867 // Create Decl objects for each parameter, adding them to the
868 // FunctionDecl.
869 const auto *FP = cast<FunctionProtoType>(FTy);
870 SmallVector<ParmVarDecl *, 4> ParmList;
871 for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
872 ParmVarDecl *Parm = ParmVarDecl::Create(
873 Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(),
874 nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr);
875 Parm->setScopeInfo(0, IParm);
876 ParmList.push_back(Parm);
878 NewOpenCLBuiltin->setParams(ParmList);
880 // Add function attributes.
881 if (OpenCLBuiltin.IsPure)
882 NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context));
883 if (OpenCLBuiltin.IsConst)
884 NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context));
885 if (OpenCLBuiltin.IsConv)
886 NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context));
888 if (!S.getLangOpts().OpenCLCPlusPlus)
889 NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context));
891 LR.addDecl(NewOpenCLBuiltin);
895 // If we added overloads, need to resolve the lookup result.
896 if (Len > 1 || HasGenType)
897 LR.resolveKind();
900 /// Lookup a builtin function, when name lookup would otherwise
901 /// fail.
902 bool Sema::LookupBuiltin(LookupResult &R) {
903 Sema::LookupNameKind NameKind = R.getLookupKind();
905 // If we didn't find a use of this identifier, and if the identifier
906 // corresponds to a compiler builtin, create the decl object for the builtin
907 // now, injecting it into translation unit scope, and return it.
908 if (NameKind == Sema::LookupOrdinaryName ||
909 NameKind == Sema::LookupRedeclarationWithLinkage) {
910 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
911 if (II) {
912 if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
913 if (II == getASTContext().getMakeIntegerSeqName()) {
914 R.addDecl(getASTContext().getMakeIntegerSeqDecl());
915 return true;
916 } else if (II == getASTContext().getTypePackElementName()) {
917 R.addDecl(getASTContext().getTypePackElementDecl());
918 return true;
922 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
923 if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {
924 auto Index = isOpenCLBuiltin(II->getName());
925 if (Index.first) {
926 InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1,
927 Index.second);
928 return true;
932 if (DeclareRISCVVBuiltins) {
933 if (!RVIntrinsicManager)
934 RVIntrinsicManager = CreateRISCVIntrinsicManager(*this);
936 if (RVIntrinsicManager->CreateIntrinsicIfFound(R, II, PP))
937 return true;
940 // If this is a builtin on this (or all) targets, create the decl.
941 if (unsigned BuiltinID = II->getBuiltinID()) {
942 // In C++, C2x, and OpenCL (spec v1.2 s6.9.f), we don't have any
943 // predefined library functions like 'malloc'. Instead, we'll just
944 // error.
945 if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL ||
946 getLangOpts().C2x) &&
947 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
948 return false;
950 if (NamedDecl *D =
951 LazilyCreateBuiltin(II, BuiltinID, TUScope,
952 R.isForRedeclaration(), R.getNameLoc())) {
953 R.addDecl(D);
954 return true;
960 return false;
963 /// Looks up the declaration of "struct objc_super" and
964 /// saves it for later use in building builtin declaration of
965 /// objc_msgSendSuper and objc_msgSendSuper_stret.
966 static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) {
967 ASTContext &Context = Sema.Context;
968 LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),
969 Sema::LookupTagName);
970 Sema.LookupName(Result, S);
971 if (Result.getResultKind() == LookupResult::Found)
972 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
973 Context.setObjCSuperType(Context.getTagDeclType(TD));
976 void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) {
977 if (ID == Builtin::BIobjc_msgSendSuper)
978 LookupPredefedObjCSuperType(*this, S);
981 /// Determine whether we can declare a special member function within
982 /// the class at this point.
983 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
984 // We need to have a definition for the class.
985 if (!Class->getDefinition() || Class->isDependentContext())
986 return false;
988 // We can't be in the middle of defining the class.
989 return !Class->isBeingDefined();
992 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
993 if (!CanDeclareSpecialMemberFunction(Class))
994 return;
996 // If the default constructor has not yet been declared, do so now.
997 if (Class->needsImplicitDefaultConstructor())
998 DeclareImplicitDefaultConstructor(Class);
1000 // If the copy constructor has not yet been declared, do so now.
1001 if (Class->needsImplicitCopyConstructor())
1002 DeclareImplicitCopyConstructor(Class);
1004 // If the copy assignment operator has not yet been declared, do so now.
1005 if (Class->needsImplicitCopyAssignment())
1006 DeclareImplicitCopyAssignment(Class);
1008 if (getLangOpts().CPlusPlus11) {
1009 // If the move constructor has not yet been declared, do so now.
1010 if (Class->needsImplicitMoveConstructor())
1011 DeclareImplicitMoveConstructor(Class);
1013 // If the move assignment operator has not yet been declared, do so now.
1014 if (Class->needsImplicitMoveAssignment())
1015 DeclareImplicitMoveAssignment(Class);
1018 // If the destructor has not yet been declared, do so now.
1019 if (Class->needsImplicitDestructor())
1020 DeclareImplicitDestructor(Class);
1023 /// Determine whether this is the name of an implicitly-declared
1024 /// special member function.
1025 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
1026 switch (Name.getNameKind()) {
1027 case DeclarationName::CXXConstructorName:
1028 case DeclarationName::CXXDestructorName:
1029 return true;
1031 case DeclarationName::CXXOperatorName:
1032 return Name.getCXXOverloadedOperator() == OO_Equal;
1034 default:
1035 break;
1038 return false;
1041 /// If there are any implicit member functions with the given name
1042 /// that need to be declared in the given declaration context, do so.
1043 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
1044 DeclarationName Name,
1045 SourceLocation Loc,
1046 const DeclContext *DC) {
1047 if (!DC)
1048 return;
1050 switch (Name.getNameKind()) {
1051 case DeclarationName::CXXConstructorName:
1052 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1053 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1054 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1055 if (Record->needsImplicitDefaultConstructor())
1056 S.DeclareImplicitDefaultConstructor(Class);
1057 if (Record->needsImplicitCopyConstructor())
1058 S.DeclareImplicitCopyConstructor(Class);
1059 if (S.getLangOpts().CPlusPlus11 &&
1060 Record->needsImplicitMoveConstructor())
1061 S.DeclareImplicitMoveConstructor(Class);
1063 break;
1065 case DeclarationName::CXXDestructorName:
1066 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1067 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
1068 CanDeclareSpecialMemberFunction(Record))
1069 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
1070 break;
1072 case DeclarationName::CXXOperatorName:
1073 if (Name.getCXXOverloadedOperator() != OO_Equal)
1074 break;
1076 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
1077 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1078 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1079 if (Record->needsImplicitCopyAssignment())
1080 S.DeclareImplicitCopyAssignment(Class);
1081 if (S.getLangOpts().CPlusPlus11 &&
1082 Record->needsImplicitMoveAssignment())
1083 S.DeclareImplicitMoveAssignment(Class);
1086 break;
1088 case DeclarationName::CXXDeductionGuideName:
1089 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
1090 break;
1092 default:
1093 break;
1097 // Adds all qualifying matches for a name within a decl context to the
1098 // given lookup result. Returns true if any matches were found.
1099 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
1100 bool Found = false;
1102 // Lazily declare C++ special member functions.
1103 if (S.getLangOpts().CPlusPlus)
1104 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
1105 DC);
1107 // Perform lookup into this declaration context.
1108 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
1109 for (NamedDecl *D : DR) {
1110 if ((D = R.getAcceptableDecl(D))) {
1111 R.addDecl(D);
1112 Found = true;
1116 if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))
1117 return true;
1119 if (R.getLookupName().getNameKind()
1120 != DeclarationName::CXXConversionFunctionName ||
1121 R.getLookupName().getCXXNameType()->isDependentType() ||
1122 !isa<CXXRecordDecl>(DC))
1123 return Found;
1125 // C++ [temp.mem]p6:
1126 // A specialization of a conversion function template is not found by
1127 // name lookup. Instead, any conversion function templates visible in the
1128 // context of the use are considered. [...]
1129 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1130 if (!Record->isCompleteDefinition())
1131 return Found;
1133 // For conversion operators, 'operator auto' should only match
1134 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
1135 // as a candidate for template substitution.
1136 auto *ContainedDeducedType =
1137 R.getLookupName().getCXXNameType()->getContainedDeducedType();
1138 if (R.getLookupName().getNameKind() ==
1139 DeclarationName::CXXConversionFunctionName &&
1140 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
1141 return Found;
1143 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
1144 UEnd = Record->conversion_end(); U != UEnd; ++U) {
1145 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
1146 if (!ConvTemplate)
1147 continue;
1149 // When we're performing lookup for the purposes of redeclaration, just
1150 // add the conversion function template. When we deduce template
1151 // arguments for specializations, we'll end up unifying the return
1152 // type of the new declaration with the type of the function template.
1153 if (R.isForRedeclaration()) {
1154 R.addDecl(ConvTemplate);
1155 Found = true;
1156 continue;
1159 // C++ [temp.mem]p6:
1160 // [...] For each such operator, if argument deduction succeeds
1161 // (14.9.2.3), the resulting specialization is used as if found by
1162 // name lookup.
1164 // When referencing a conversion function for any purpose other than
1165 // a redeclaration (such that we'll be building an expression with the
1166 // result), perform template argument deduction and place the
1167 // specialization into the result set. We do this to avoid forcing all
1168 // callers to perform special deduction for conversion functions.
1169 TemplateDeductionInfo Info(R.getNameLoc());
1170 FunctionDecl *Specialization = nullptr;
1172 const FunctionProtoType *ConvProto
1173 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
1174 assert(ConvProto && "Nonsensical conversion function template type");
1176 // Compute the type of the function that we would expect the conversion
1177 // function to have, if it were to match the name given.
1178 // FIXME: Calling convention!
1179 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
1180 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
1181 EPI.ExceptionSpec = EST_None;
1182 QualType ExpectedType
1183 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
1184 None, EPI);
1186 // Perform template argument deduction against the type that we would
1187 // expect the function to have.
1188 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
1189 Specialization, Info)
1190 == Sema::TDK_Success) {
1191 R.addDecl(Specialization);
1192 Found = true;
1196 return Found;
1199 // Performs C++ unqualified lookup into the given file context.
1200 static bool
1201 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
1202 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
1204 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
1206 // Perform direct name lookup into the LookupCtx.
1207 bool Found = LookupDirect(S, R, NS);
1209 // Perform direct name lookup into the namespaces nominated by the
1210 // using directives whose common ancestor is this namespace.
1211 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
1212 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
1213 Found = true;
1215 R.resolveKind();
1217 return Found;
1220 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
1221 if (DeclContext *Ctx = S->getEntity())
1222 return Ctx->isFileContext();
1223 return false;
1226 /// Find the outer declaration context from this scope. This indicates the
1227 /// context that we should search up to (exclusive) before considering the
1228 /// parent of the specified scope.
1229 static DeclContext *findOuterContext(Scope *S) {
1230 for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())
1231 if (DeclContext *DC = OuterS->getLookupEntity())
1232 return DC;
1233 return nullptr;
1236 namespace {
1237 /// An RAII object to specify that we want to find block scope extern
1238 /// declarations.
1239 struct FindLocalExternScope {
1240 FindLocalExternScope(LookupResult &R)
1241 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1242 Decl::IDNS_LocalExtern) {
1243 R.setFindLocalExtern(R.getIdentifierNamespace() &
1244 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
1246 void restore() {
1247 R.setFindLocalExtern(OldFindLocalExtern);
1249 ~FindLocalExternScope() {
1250 restore();
1252 LookupResult &R;
1253 bool OldFindLocalExtern;
1255 } // end anonymous namespace
1257 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
1258 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
1260 DeclarationName Name = R.getLookupName();
1261 Sema::LookupNameKind NameKind = R.getLookupKind();
1263 // If this is the name of an implicitly-declared special member function,
1264 // go through the scope stack to implicitly declare
1265 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1266 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1267 if (DeclContext *DC = PreS->getEntity())
1268 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
1271 // Implicitly declare member functions with the name we're looking for, if in
1272 // fact we are in a scope where it matters.
1274 Scope *Initial = S;
1275 IdentifierResolver::iterator
1276 I = IdResolver.begin(Name),
1277 IEnd = IdResolver.end();
1279 // First we lookup local scope.
1280 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1281 // ...During unqualified name lookup (3.4.1), the names appear as if
1282 // they were declared in the nearest enclosing namespace which contains
1283 // both the using-directive and the nominated namespace.
1284 // [Note: in this context, "contains" means "contains directly or
1285 // indirectly".
1287 // For example:
1288 // namespace A { int i; }
1289 // void foo() {
1290 // int i;
1291 // {
1292 // using namespace A;
1293 // ++i; // finds local 'i', A::i appears at global scope
1294 // }
1295 // }
1297 UnqualUsingDirectiveSet UDirs(*this);
1298 bool VisitedUsingDirectives = false;
1299 bool LeftStartingScope = false;
1301 // When performing a scope lookup, we want to find local extern decls.
1302 FindLocalExternScope FindLocals(R);
1304 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1305 bool SearchNamespaceScope = true;
1306 // Check whether the IdResolver has anything in this scope.
1307 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1308 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1309 if (NameKind == LookupRedeclarationWithLinkage &&
1310 !(*I)->isTemplateParameter()) {
1311 // If it's a template parameter, we still find it, so we can diagnose
1312 // the invalid redeclaration.
1314 // Determine whether this (or a previous) declaration is
1315 // out-of-scope.
1316 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1317 LeftStartingScope = true;
1319 // If we found something outside of our starting scope that
1320 // does not have linkage, skip it.
1321 if (LeftStartingScope && !((*I)->hasLinkage())) {
1322 R.setShadowed();
1323 continue;
1325 } else {
1326 // We found something in this scope, we should not look at the
1327 // namespace scope
1328 SearchNamespaceScope = false;
1330 R.addDecl(ND);
1333 if (!SearchNamespaceScope) {
1334 R.resolveKind();
1335 if (S->isClassScope())
1336 if (CXXRecordDecl *Record =
1337 dyn_cast_or_null<CXXRecordDecl>(S->getEntity()))
1338 R.setNamingClass(Record);
1339 return true;
1342 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1343 // C++11 [class.friend]p11:
1344 // If a friend declaration appears in a local class and the name
1345 // specified is an unqualified name, a prior declaration is
1346 // looked up without considering scopes that are outside the
1347 // innermost enclosing non-class scope.
1348 return false;
1351 if (DeclContext *Ctx = S->getLookupEntity()) {
1352 DeclContext *OuterCtx = findOuterContext(S);
1353 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1354 // We do not directly look into transparent contexts, since
1355 // those entities will be found in the nearest enclosing
1356 // non-transparent context.
1357 if (Ctx->isTransparentContext())
1358 continue;
1360 // We do not look directly into function or method contexts,
1361 // since all of the local variables and parameters of the
1362 // function/method are present within the Scope.
1363 if (Ctx->isFunctionOrMethod()) {
1364 // If we have an Objective-C instance method, look for ivars
1365 // in the corresponding interface.
1366 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1367 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1368 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1369 ObjCInterfaceDecl *ClassDeclared;
1370 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1371 Name.getAsIdentifierInfo(),
1372 ClassDeclared)) {
1373 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1374 R.addDecl(ND);
1375 R.resolveKind();
1376 return true;
1382 continue;
1385 // If this is a file context, we need to perform unqualified name
1386 // lookup considering using directives.
1387 if (Ctx->isFileContext()) {
1388 // If we haven't handled using directives yet, do so now.
1389 if (!VisitedUsingDirectives) {
1390 // Add using directives from this context up to the top level.
1391 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1392 if (UCtx->isTransparentContext())
1393 continue;
1395 UDirs.visit(UCtx, UCtx);
1398 // Find the innermost file scope, so we can add using directives
1399 // from local scopes.
1400 Scope *InnermostFileScope = S;
1401 while (InnermostFileScope &&
1402 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1403 InnermostFileScope = InnermostFileScope->getParent();
1404 UDirs.visitScopeChain(Initial, InnermostFileScope);
1406 UDirs.done();
1408 VisitedUsingDirectives = true;
1411 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1412 R.resolveKind();
1413 return true;
1416 continue;
1419 // Perform qualified name lookup into this context.
1420 // FIXME: In some cases, we know that every name that could be found by
1421 // this qualified name lookup will also be on the identifier chain. For
1422 // example, inside a class without any base classes, we never need to
1423 // perform qualified lookup because all of the members are on top of the
1424 // identifier chain.
1425 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1426 return true;
1431 // Stop if we ran out of scopes.
1432 // FIXME: This really, really shouldn't be happening.
1433 if (!S) return false;
1435 // If we are looking for members, no need to look into global/namespace scope.
1436 if (NameKind == LookupMemberName)
1437 return false;
1439 // Collect UsingDirectiveDecls in all scopes, and recursively all
1440 // nominated namespaces by those using-directives.
1442 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1443 // don't build it for each lookup!
1444 if (!VisitedUsingDirectives) {
1445 UDirs.visitScopeChain(Initial, S);
1446 UDirs.done();
1449 // If we're not performing redeclaration lookup, do not look for local
1450 // extern declarations outside of a function scope.
1451 if (!R.isForRedeclaration())
1452 FindLocals.restore();
1454 // Lookup namespace scope, and global scope.
1455 // Unqualified name lookup in C++ requires looking into scopes
1456 // that aren't strictly lexical, and therefore we walk through the
1457 // context as well as walking through the scopes.
1458 for (; S; S = S->getParent()) {
1459 // Check whether the IdResolver has anything in this scope.
1460 bool Found = false;
1461 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1462 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1463 // We found something. Look for anything else in our scope
1464 // with this same name and in an acceptable identifier
1465 // namespace, so that we can construct an overload set if we
1466 // need to.
1467 Found = true;
1468 R.addDecl(ND);
1472 if (Found && S->isTemplateParamScope()) {
1473 R.resolveKind();
1474 return true;
1477 DeclContext *Ctx = S->getLookupEntity();
1478 if (Ctx) {
1479 DeclContext *OuterCtx = findOuterContext(S);
1480 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1481 // We do not directly look into transparent contexts, since
1482 // those entities will be found in the nearest enclosing
1483 // non-transparent context.
1484 if (Ctx->isTransparentContext())
1485 continue;
1487 // If we have a context, and it's not a context stashed in the
1488 // template parameter scope for an out-of-line definition, also
1489 // look into that context.
1490 if (!(Found && S->isTemplateParamScope())) {
1491 assert(Ctx->isFileContext() &&
1492 "We should have been looking only at file context here already.");
1494 // Look into context considering using-directives.
1495 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1496 Found = true;
1499 if (Found) {
1500 R.resolveKind();
1501 return true;
1504 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1505 return false;
1509 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1510 return false;
1513 return !R.empty();
1516 void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1517 if (auto *M = getCurrentModule())
1518 Context.mergeDefinitionIntoModule(ND, M);
1519 else
1520 // We're not building a module; just make the definition visible.
1521 ND->setVisibleDespiteOwningModule();
1523 // If ND is a template declaration, make the template parameters
1524 // visible too. They're not (necessarily) within a mergeable DeclContext.
1525 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1526 for (auto *Param : *TD->getTemplateParameters())
1527 makeMergedDefinitionVisible(Param);
1530 /// Find the module in which the given declaration was defined.
1531 static Module *getDefiningModule(Sema &S, Decl *Entity) {
1532 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1533 // If this function was instantiated from a template, the defining module is
1534 // the module containing the pattern.
1535 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1536 Entity = Pattern;
1537 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1538 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1539 Entity = Pattern;
1540 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1541 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1542 Entity = Pattern;
1543 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1544 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1545 Entity = Pattern;
1548 // Walk up to the containing context. That might also have been instantiated
1549 // from a template.
1550 DeclContext *Context = Entity->getLexicalDeclContext();
1551 if (Context->isFileContext())
1552 return S.getOwningModule(Entity);
1553 return getDefiningModule(S, cast<Decl>(Context));
1556 llvm::DenseSet<Module*> &Sema::getLookupModules() {
1557 unsigned N = CodeSynthesisContexts.size();
1558 for (unsigned I = CodeSynthesisContextLookupModules.size();
1559 I != N; ++I) {
1560 Module *M = CodeSynthesisContexts[I].Entity ?
1561 getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
1562 nullptr;
1563 if (M && !LookupModulesCache.insert(M).second)
1564 M = nullptr;
1565 CodeSynthesisContextLookupModules.push_back(M);
1567 return LookupModulesCache;
1570 /// Determine if we could use all the declarations in the module.
1571 bool Sema::isUsableModule(const Module *M) {
1572 assert(M && "We shouldn't check nullness for module here");
1573 // Return quickly if we cached the result.
1574 if (UsableModuleUnitsCache.count(M))
1575 return true;
1577 // If M is the global module fragment of the current translation unit. So it
1578 // should be usable.
1579 // [module.global.frag]p1:
1580 // The global module fragment can be used to provide declarations that are
1581 // attached to the global module and usable within the module unit.
1582 if (M == GlobalModuleFragment ||
1583 // If M is the module we're parsing, it should be usable. This covers the
1584 // private module fragment. The private module fragment is usable only if
1585 // it is within the current module unit. And it must be the current
1586 // parsing module unit if it is within the current module unit according
1587 // to the grammar of the private module fragment. NOTE: This is covered by
1588 // the following condition. The intention of the check is to avoid string
1589 // comparison as much as possible.
1590 M == getCurrentModule() ||
1591 // The module unit which is in the same module with the current module
1592 // unit is usable.
1594 // FIXME: Here we judge if they are in the same module by comparing the
1595 // string. Is there any better solution?
1596 M->getPrimaryModuleInterfaceName() ==
1597 llvm::StringRef(getLangOpts().CurrentModule).split(':').first) {
1598 UsableModuleUnitsCache.insert(M);
1599 return true;
1602 return false;
1605 bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1606 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1607 if (isModuleVisible(Merged))
1608 return true;
1609 return false;
1612 bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
1613 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1614 if (isUsableModule(Merged))
1615 return true;
1616 return false;
1619 template <typename ParmDecl>
1620 static bool
1621 hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D,
1622 llvm::SmallVectorImpl<Module *> *Modules,
1623 Sema::AcceptableKind Kind) {
1624 if (!D->hasDefaultArgument())
1625 return false;
1627 llvm::SmallDenseSet<const ParmDecl *, 4> Visited;
1628 while (D && !Visited.count(D)) {
1629 Visited.insert(D);
1631 auto &DefaultArg = D->getDefaultArgStorage();
1632 if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))
1633 return true;
1635 if (!DefaultArg.isInherited() && Modules) {
1636 auto *NonConstD = const_cast<ParmDecl*>(D);
1637 Modules->push_back(S.getOwningModule(NonConstD));
1640 // If there was a previous default argument, maybe its parameter is
1641 // acceptable.
1642 D = DefaultArg.getInheritedFrom();
1644 return false;
1647 bool Sema::hasAcceptableDefaultArgument(
1648 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,
1649 Sema::AcceptableKind Kind) {
1650 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1651 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1653 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1654 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1656 return ::hasAcceptableDefaultArgument(
1657 *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);
1660 bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1661 llvm::SmallVectorImpl<Module *> *Modules) {
1662 return hasAcceptableDefaultArgument(D, Modules,
1663 Sema::AcceptableKind::Visible);
1666 bool Sema::hasReachableDefaultArgument(
1667 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1668 return hasAcceptableDefaultArgument(D, Modules,
1669 Sema::AcceptableKind::Reachable);
1672 template <typename Filter>
1673 static bool
1674 hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D,
1675 llvm::SmallVectorImpl<Module *> *Modules, Filter F,
1676 Sema::AcceptableKind Kind) {
1677 bool HasFilteredRedecls = false;
1679 for (auto *Redecl : D->redecls()) {
1680 auto *R = cast<NamedDecl>(Redecl);
1681 if (!F(R))
1682 continue;
1684 if (S.isAcceptable(R, Kind))
1685 return true;
1687 HasFilteredRedecls = true;
1689 if (Modules)
1690 Modules->push_back(R->getOwningModule());
1693 // Only return false if there is at least one redecl that is not filtered out.
1694 if (HasFilteredRedecls)
1695 return false;
1697 return true;
1700 static bool
1701 hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D,
1702 llvm::SmallVectorImpl<Module *> *Modules,
1703 Sema::AcceptableKind Kind) {
1704 return hasAcceptableDeclarationImpl(
1705 S, D, Modules,
1706 [](const NamedDecl *D) {
1707 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1708 return RD->getTemplateSpecializationKind() ==
1709 TSK_ExplicitSpecialization;
1710 if (auto *FD = dyn_cast<FunctionDecl>(D))
1711 return FD->getTemplateSpecializationKind() ==
1712 TSK_ExplicitSpecialization;
1713 if (auto *VD = dyn_cast<VarDecl>(D))
1714 return VD->getTemplateSpecializationKind() ==
1715 TSK_ExplicitSpecialization;
1716 llvm_unreachable("unknown explicit specialization kind");
1718 Kind);
1721 bool Sema::hasVisibleExplicitSpecialization(
1722 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1723 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1724 Sema::AcceptableKind::Visible);
1727 bool Sema::hasReachableExplicitSpecialization(
1728 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1729 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1730 Sema::AcceptableKind::Reachable);
1733 static bool
1734 hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D,
1735 llvm::SmallVectorImpl<Module *> *Modules,
1736 Sema::AcceptableKind Kind) {
1737 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1738 "not a member specialization");
1739 return hasAcceptableDeclarationImpl(
1740 S, D, Modules,
1741 [](const NamedDecl *D) {
1742 // If the specialization is declared at namespace scope, then it's a
1743 // member specialization declaration. If it's lexically inside the class
1744 // definition then it was instantiated.
1746 // FIXME: This is a hack. There should be a better way to determine
1747 // this.
1748 // FIXME: What about MS-style explicit specializations declared within a
1749 // class definition?
1750 return D->getLexicalDeclContext()->isFileContext();
1752 Kind);
1755 bool Sema::hasVisibleMemberSpecialization(
1756 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1757 return hasAcceptableMemberSpecialization(*this, D, Modules,
1758 Sema::AcceptableKind::Visible);
1761 bool Sema::hasReachableMemberSpecialization(
1762 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1763 return hasAcceptableMemberSpecialization(*this, D, Modules,
1764 Sema::AcceptableKind::Reachable);
1767 /// Determine whether a declaration is acceptable to name lookup.
1769 /// This routine determines whether the declaration D is acceptable in the
1770 /// current lookup context, taking into account the current template
1771 /// instantiation stack. During template instantiation, a declaration is
1772 /// acceptable if it is acceptable from a module containing any entity on the
1773 /// template instantiation path (by instantiating a template, you allow it to
1774 /// see the declarations that your module can see, including those later on in
1775 /// your module).
1776 bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
1777 Sema::AcceptableKind Kind) {
1778 assert(!D->isUnconditionallyVisible() &&
1779 "should not call this: not in slow case");
1781 Module *DeclModule = SemaRef.getOwningModule(D);
1782 assert(DeclModule && "hidden decl has no owning module");
1784 // If the owning module is visible, the decl is acceptable.
1785 if (SemaRef.isModuleVisible(DeclModule,
1786 D->isInvisibleOutsideTheOwningModule()))
1787 return true;
1789 // Determine whether a decl context is a file context for the purpose of
1790 // visibility/reachability. This looks through some (export and linkage spec)
1791 // transparent contexts, but not others (enums).
1792 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1793 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1794 isa<ExportDecl>(DC);
1797 // If this declaration is not at namespace scope
1798 // then it is acceptable if its lexical parent has a acceptable definition.
1799 DeclContext *DC = D->getLexicalDeclContext();
1800 if (DC && !IsEffectivelyFileContext(DC)) {
1801 // For a parameter, check whether our current template declaration's
1802 // lexical context is acceptable, not whether there's some other acceptable
1803 // definition of it, because parameters aren't "within" the definition.
1805 // In C++ we need to check for a acceptable definition due to ODR merging,
1806 // and in C we must not because each declaration of a function gets its own
1807 // set of declarations for tags in prototype scope.
1808 bool AcceptableWithinParent;
1809 if (D->isTemplateParameter()) {
1810 bool SearchDefinitions = true;
1811 if (const auto *DCD = dyn_cast<Decl>(DC)) {
1812 if (const auto *TD = DCD->getDescribedTemplate()) {
1813 TemplateParameterList *TPL = TD->getTemplateParameters();
1814 auto Index = getDepthAndIndex(D).second;
1815 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1818 if (SearchDefinitions)
1819 AcceptableWithinParent =
1820 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1821 else
1822 AcceptableWithinParent =
1823 isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1824 } else if (isa<ParmVarDecl>(D) ||
1825 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1826 AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1827 else if (D->isModulePrivate()) {
1828 // A module-private declaration is only acceptable if an enclosing lexical
1829 // parent was merged with another definition in the current module.
1830 AcceptableWithinParent = false;
1831 do {
1832 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1833 AcceptableWithinParent = true;
1834 break;
1836 DC = DC->getLexicalParent();
1837 } while (!IsEffectivelyFileContext(DC));
1838 } else {
1839 AcceptableWithinParent =
1840 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1843 if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1844 Kind == Sema::AcceptableKind::Visible &&
1845 // FIXME: Do something better in this case.
1846 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1847 // Cache the fact that this declaration is implicitly visible because
1848 // its parent has a visible definition.
1849 D->setVisibleDespiteOwningModule();
1851 return AcceptableWithinParent;
1854 if (Kind == Sema::AcceptableKind::Visible)
1855 return false;
1857 assert(Kind == Sema::AcceptableKind::Reachable &&
1858 "Additional Sema::AcceptableKind?");
1859 return isReachableSlow(SemaRef, D);
1862 bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1863 // [module.global.frag]p2:
1864 // A global-module-fragment specifies the contents of the global module
1865 // fragment for a module unit. The global module fragment can be used to
1866 // provide declarations that are attached to the global module and usable
1867 // within the module unit.
1869 // Global module fragment is special. Global Module fragment is only usable
1870 // within the module unit it got defined [module.global.frag]p2. So here we
1871 // check if the Module is the global module fragment in current translation
1872 // unit.
1873 if (M->isGlobalModule() && M != this->GlobalModuleFragment)
1874 return false;
1876 // The module might be ordinarily visible. For a module-private query, that
1877 // means it is part of the current module.
1878 if (ModulePrivate && isUsableModule(M))
1879 return true;
1881 // For a query which is not module-private, that means it is in our visible
1882 // module set.
1883 if (!ModulePrivate && VisibleModules.isVisible(M))
1884 return true;
1886 // Otherwise, it might be visible by virtue of the query being within a
1887 // template instantiation or similar that is permitted to look inside M.
1889 // Find the extra places where we need to look.
1890 const auto &LookupModules = getLookupModules();
1891 if (LookupModules.empty())
1892 return false;
1894 // If our lookup set contains the module, it's visible.
1895 if (LookupModules.count(M))
1896 return true;
1898 // For a module-private query, that's everywhere we get to look.
1899 if (ModulePrivate)
1900 return false;
1902 // Check whether M is transitively exported to an import of the lookup set.
1903 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1904 return LookupM->isModuleVisible(M);
1908 // FIXME: Return false directly if we don't have an interface dependency on the
1909 // translation unit containing D.
1910 bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
1911 assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
1913 Module *DeclModule = SemaRef.getOwningModule(D);
1914 assert(DeclModule && "hidden decl has no owning module");
1916 // Entities in module map modules are reachable only if they're visible.
1917 if (DeclModule->isModuleMapModule())
1918 return false;
1920 // If D comes from a module and SemaRef doesn't own a module, it implies D
1921 // comes from another TU. In case SemaRef owns a module, we could judge if D
1922 // comes from another TU by comparing the module unit.
1923 if (SemaRef.isModuleUnitOfCurrentTU(DeclModule))
1924 return true;
1926 // [module.reach]/p3:
1927 // A declaration D is reachable from a point P if:
1928 // ...
1929 // - D is not discarded ([module.global.frag]), appears in a translation unit
1930 // that is reachable from P, and does not appear within a private module
1931 // fragment.
1933 // A declaration that's discarded in the GMF should be module-private.
1934 if (D->isModulePrivate())
1935 return false;
1937 // [module.reach]/p1
1938 // A translation unit U is necessarily reachable from a point P if U is a
1939 // module interface unit on which the translation unit containing P has an
1940 // interface dependency, or the translation unit containing P imports U, in
1941 // either case prior to P ([module.import]).
1943 // [module.import]/p10
1944 // A translation unit has an interface dependency on a translation unit U if
1945 // it contains a declaration (possibly a module-declaration) that imports U
1946 // or if it has an interface dependency on a translation unit that has an
1947 // interface dependency on U.
1949 // So we could conclude the module unit U is necessarily reachable if:
1950 // (1) The module unit U is module interface unit.
1951 // (2) The current unit has an interface dependency on the module unit U.
1953 // Here we only check for the first condition. Since we couldn't see
1954 // DeclModule if it isn't (transitively) imported.
1955 if (DeclModule->getTopLevelModule()->isModuleInterfaceUnit())
1956 return true;
1958 // [module.reach]/p2
1959 // Additional translation units on
1960 // which the point within the program has an interface dependency may be
1961 // considered reachable, but it is unspecified which are and under what
1962 // circumstances.
1964 // The decision here is to treat all additional tranditional units as
1965 // unreachable.
1966 return false;
1969 bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {
1970 return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);
1973 bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1974 // FIXME: If there are both visible and hidden declarations, we need to take
1975 // into account whether redeclaration is possible. Example:
1977 // Non-imported module:
1978 // int f(T); // #1
1979 // Some TU:
1980 // static int f(U); // #2, not a redeclaration of #1
1981 // int f(T); // #3, finds both, should link with #1 if T != U, but
1982 // // with #2 if T == U; neither should be ambiguous.
1983 for (auto *D : R) {
1984 if (isVisible(D))
1985 return true;
1986 assert(D->isExternallyDeclarable() &&
1987 "should not have hidden, non-externally-declarable result here");
1990 // This function is called once "New" is essentially complete, but before a
1991 // previous declaration is attached. We can't query the linkage of "New" in
1992 // general, because attaching the previous declaration can change the
1993 // linkage of New to match the previous declaration.
1995 // However, because we've just determined that there is no *visible* prior
1996 // declaration, we can compute the linkage here. There are two possibilities:
1998 // * This is not a redeclaration; it's safe to compute the linkage now.
2000 // * This is a redeclaration of a prior declaration that is externally
2001 // redeclarable. In that case, the linkage of the declaration is not
2002 // changed by attaching the prior declaration, because both are externally
2003 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
2005 // FIXME: This is subtle and fragile.
2006 return New->isExternallyDeclarable();
2009 /// Retrieve the visible declaration corresponding to D, if any.
2011 /// This routine determines whether the declaration D is visible in the current
2012 /// module, with the current imports. If not, it checks whether any
2013 /// redeclaration of D is visible, and if so, returns that declaration.
2015 /// \returns D, or a visible previous declaration of D, whichever is more recent
2016 /// and visible. If no declaration of D is visible, returns null.
2017 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
2018 unsigned IDNS) {
2019 assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");
2021 for (auto *RD : D->redecls()) {
2022 // Don't bother with extra checks if we already know this one isn't visible.
2023 if (RD == D)
2024 continue;
2026 auto ND = cast<NamedDecl>(RD);
2027 // FIXME: This is wrong in the case where the previous declaration is not
2028 // visible in the same scope as D. This needs to be done much more
2029 // carefully.
2030 if (ND->isInIdentifierNamespace(IDNS) &&
2031 LookupResult::isAvailableForLookup(SemaRef, ND))
2032 return ND;
2035 return nullptr;
2038 bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
2039 llvm::SmallVectorImpl<Module *> *Modules) {
2040 assert(!isVisible(D) && "not in slow case");
2041 return hasAcceptableDeclarationImpl(
2042 *this, D, Modules, [](const NamedDecl *) { return true; },
2043 Sema::AcceptableKind::Visible);
2046 bool Sema::hasReachableDeclarationSlow(
2047 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
2048 assert(!isReachable(D) && "not in slow case");
2049 return hasAcceptableDeclarationImpl(
2050 *this, D, Modules, [](const NamedDecl *) { return true; },
2051 Sema::AcceptableKind::Reachable);
2054 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
2055 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
2056 // Namespaces are a bit of a special case: we expect there to be a lot of
2057 // redeclarations of some namespaces, all declarations of a namespace are
2058 // essentially interchangeable, all declarations are found by name lookup
2059 // if any is, and namespaces are never looked up during template
2060 // instantiation. So we benefit from caching the check in this case, and
2061 // it is correct to do so.
2062 auto *Key = ND->getCanonicalDecl();
2063 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
2064 return Acceptable;
2065 auto *Acceptable = isVisible(getSema(), Key)
2066 ? Key
2067 : findAcceptableDecl(getSema(), Key, IDNS);
2068 if (Acceptable)
2069 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
2070 return Acceptable;
2073 return findAcceptableDecl(getSema(), D, IDNS);
2076 bool LookupResult::isVisible(Sema &SemaRef, NamedDecl *D) {
2077 // If this declaration is already visible, return it directly.
2078 if (D->isUnconditionallyVisible())
2079 return true;
2081 // During template instantiation, we can refer to hidden declarations, if
2082 // they were visible in any module along the path of instantiation.
2083 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);
2086 bool LookupResult::isReachable(Sema &SemaRef, NamedDecl *D) {
2087 if (D->isUnconditionallyVisible())
2088 return true;
2090 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);
2093 bool LookupResult::isAvailableForLookup(Sema &SemaRef, NamedDecl *ND) {
2094 // We should check the visibility at the callsite already.
2095 if (isVisible(SemaRef, ND))
2096 return true;
2098 // Deduction guide lives in namespace scope generally, but it is just a
2099 // hint to the compilers. What we actually lookup for is the generated member
2100 // of the corresponding template. So it is sufficient to check the
2101 // reachability of the template decl.
2102 if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())
2103 return SemaRef.hasReachableDefinition(DeductionGuide);
2105 auto *DC = ND->getDeclContext();
2106 // If ND is not visible and it is at namespace scope, it shouldn't be found
2107 // by name lookup.
2108 if (DC->isFileContext())
2109 return false;
2111 // [module.interface]p7
2112 // Class and enumeration member names can be found by name lookup in any
2113 // context in which a definition of the type is reachable.
2115 // FIXME: The current implementation didn't consider about scope. For example,
2116 // ```
2117 // // m.cppm
2118 // export module m;
2119 // enum E1 { e1 };
2120 // // Use.cpp
2121 // import m;
2122 // void test() {
2123 // auto a = E1::e1; // Error as expected.
2124 // auto b = e1; // Should be error. namespace-scope name e1 is not visible
2125 // }
2126 // ```
2127 // For the above example, the current implementation would emit error for `a`
2128 // correctly. However, the implementation wouldn't diagnose about `b` now.
2129 // Since we only check the reachability for the parent only.
2130 // See clang/test/CXX/module/module.interface/p7.cpp for example.
2131 if (auto *TD = dyn_cast<TagDecl>(DC))
2132 return SemaRef.hasReachableDefinition(TD);
2134 return false;
2137 /// Perform unqualified name lookup starting from a given
2138 /// scope.
2140 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
2141 /// used to find names within the current scope. For example, 'x' in
2142 /// @code
2143 /// int x;
2144 /// int f() {
2145 /// return x; // unqualified name look finds 'x' in the global scope
2146 /// }
2147 /// @endcode
2149 /// Different lookup criteria can find different names. For example, a
2150 /// particular scope can have both a struct and a function of the same
2151 /// name, and each can be found by certain lookup criteria. For more
2152 /// information about lookup criteria, see the documentation for the
2153 /// class LookupCriteria.
2155 /// @param S The scope from which unqualified name lookup will
2156 /// begin. If the lookup criteria permits, name lookup may also search
2157 /// in the parent scopes.
2159 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
2160 /// look up and the lookup kind), and is updated with the results of lookup
2161 /// including zero or more declarations and possibly additional information
2162 /// used to diagnose ambiguities.
2164 /// @returns \c true if lookup succeeded and false otherwise.
2165 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
2166 bool ForceNoCPlusPlus) {
2167 DeclarationName Name = R.getLookupName();
2168 if (!Name) return false;
2170 LookupNameKind NameKind = R.getLookupKind();
2172 if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
2173 // Unqualified name lookup in C/Objective-C is purely lexical, so
2174 // search in the declarations attached to the name.
2175 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
2176 // Find the nearest non-transparent declaration scope.
2177 while (!(S->getFlags() & Scope::DeclScope) ||
2178 (S->getEntity() && S->getEntity()->isTransparentContext()))
2179 S = S->getParent();
2182 // When performing a scope lookup, we want to find local extern decls.
2183 FindLocalExternScope FindLocals(R);
2185 // Scan up the scope chain looking for a decl that matches this
2186 // identifier that is in the appropriate namespace. This search
2187 // should not take long, as shadowing of names is uncommon, and
2188 // deep shadowing is extremely uncommon.
2189 bool LeftStartingScope = false;
2191 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2192 IEnd = IdResolver.end();
2193 I != IEnd; ++I)
2194 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
2195 if (NameKind == LookupRedeclarationWithLinkage) {
2196 // Determine whether this (or a previous) declaration is
2197 // out-of-scope.
2198 if (!LeftStartingScope && !S->isDeclScope(*I))
2199 LeftStartingScope = true;
2201 // If we found something outside of our starting scope that
2202 // does not have linkage, skip it.
2203 if (LeftStartingScope && !((*I)->hasLinkage())) {
2204 R.setShadowed();
2205 continue;
2208 else if (NameKind == LookupObjCImplicitSelfParam &&
2209 !isa<ImplicitParamDecl>(*I))
2210 continue;
2212 R.addDecl(D);
2214 // Check whether there are any other declarations with the same name
2215 // and in the same scope.
2216 if (I != IEnd) {
2217 // Find the scope in which this declaration was declared (if it
2218 // actually exists in a Scope).
2219 while (S && !S->isDeclScope(D))
2220 S = S->getParent();
2222 // If the scope containing the declaration is the translation unit,
2223 // then we'll need to perform our checks based on the matching
2224 // DeclContexts rather than matching scopes.
2225 if (S && isNamespaceOrTranslationUnitScope(S))
2226 S = nullptr;
2228 // Compute the DeclContext, if we need it.
2229 DeclContext *DC = nullptr;
2230 if (!S)
2231 DC = (*I)->getDeclContext()->getRedeclContext();
2233 IdentifierResolver::iterator LastI = I;
2234 for (++LastI; LastI != IEnd; ++LastI) {
2235 if (S) {
2236 // Match based on scope.
2237 if (!S->isDeclScope(*LastI))
2238 break;
2239 } else {
2240 // Match based on DeclContext.
2241 DeclContext *LastDC
2242 = (*LastI)->getDeclContext()->getRedeclContext();
2243 if (!LastDC->Equals(DC))
2244 break;
2247 // If the declaration is in the right namespace and visible, add it.
2248 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
2249 R.addDecl(LastD);
2252 R.resolveKind();
2255 return true;
2257 } else {
2258 // Perform C++ unqualified name lookup.
2259 if (CppLookupName(R, S))
2260 return true;
2263 // If we didn't find a use of this identifier, and if the identifier
2264 // corresponds to a compiler builtin, create the decl object for the builtin
2265 // now, injecting it into translation unit scope, and return it.
2266 if (AllowBuiltinCreation && LookupBuiltin(R))
2267 return true;
2269 // If we didn't find a use of this identifier, the ExternalSource
2270 // may be able to handle the situation.
2271 // Note: some lookup failures are expected!
2272 // See e.g. R.isForRedeclaration().
2273 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2276 /// Perform qualified name lookup in the namespaces nominated by
2277 /// using directives by the given context.
2279 /// C++98 [namespace.qual]p2:
2280 /// Given X::m (where X is a user-declared namespace), or given \::m
2281 /// (where X is the global namespace), let S be the set of all
2282 /// declarations of m in X and in the transitive closure of all
2283 /// namespaces nominated by using-directives in X and its used
2284 /// namespaces, except that using-directives are ignored in any
2285 /// namespace, including X, directly containing one or more
2286 /// declarations of m. No namespace is searched more than once in
2287 /// the lookup of a name. If S is the empty set, the program is
2288 /// ill-formed. Otherwise, if S has exactly one member, or if the
2289 /// context of the reference is a using-declaration
2290 /// (namespace.udecl), S is the required set of declarations of
2291 /// m. Otherwise if the use of m is not one that allows a unique
2292 /// declaration to be chosen from S, the program is ill-formed.
2294 /// C++98 [namespace.qual]p5:
2295 /// During the lookup of a qualified namespace member name, if the
2296 /// lookup finds more than one declaration of the member, and if one
2297 /// declaration introduces a class name or enumeration name and the
2298 /// other declarations either introduce the same object, the same
2299 /// enumerator or a set of functions, the non-type name hides the
2300 /// class or enumeration name if and only if the declarations are
2301 /// from the same namespace; otherwise (the declarations are from
2302 /// different namespaces), the program is ill-formed.
2303 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
2304 DeclContext *StartDC) {
2305 assert(StartDC->isFileContext() && "start context is not a file context");
2307 // We have not yet looked into these namespaces, much less added
2308 // their "using-children" to the queue.
2309 SmallVector<NamespaceDecl*, 8> Queue;
2311 // We have at least added all these contexts to the queue.
2312 llvm::SmallPtrSet<DeclContext*, 8> Visited;
2313 Visited.insert(StartDC);
2315 // We have already looked into the initial namespace; seed the queue
2316 // with its using-children.
2317 for (auto *I : StartDC->using_directives()) {
2318 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
2319 if (S.isVisible(I) && Visited.insert(ND).second)
2320 Queue.push_back(ND);
2323 // The easiest way to implement the restriction in [namespace.qual]p5
2324 // is to check whether any of the individual results found a tag
2325 // and, if so, to declare an ambiguity if the final result is not
2326 // a tag.
2327 bool FoundTag = false;
2328 bool FoundNonTag = false;
2330 LookupResult LocalR(LookupResult::Temporary, R);
2332 bool Found = false;
2333 while (!Queue.empty()) {
2334 NamespaceDecl *ND = Queue.pop_back_val();
2336 // We go through some convolutions here to avoid copying results
2337 // between LookupResults.
2338 bool UseLocal = !R.empty();
2339 LookupResult &DirectR = UseLocal ? LocalR : R;
2340 bool FoundDirect = LookupDirect(S, DirectR, ND);
2342 if (FoundDirect) {
2343 // First do any local hiding.
2344 DirectR.resolveKind();
2346 // If the local result is a tag, remember that.
2347 if (DirectR.isSingleTagDecl())
2348 FoundTag = true;
2349 else
2350 FoundNonTag = true;
2352 // Append the local results to the total results if necessary.
2353 if (UseLocal) {
2354 R.addAllDecls(LocalR);
2355 LocalR.clear();
2359 // If we find names in this namespace, ignore its using directives.
2360 if (FoundDirect) {
2361 Found = true;
2362 continue;
2365 for (auto *I : ND->using_directives()) {
2366 NamespaceDecl *Nom = I->getNominatedNamespace();
2367 if (S.isVisible(I) && Visited.insert(Nom).second)
2368 Queue.push_back(Nom);
2372 if (Found) {
2373 if (FoundTag && FoundNonTag)
2374 R.setAmbiguousQualifiedTagHiding();
2375 else
2376 R.resolveKind();
2379 return Found;
2382 /// Perform qualified name lookup into a given context.
2384 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2385 /// names when the context of those names is explicit specified, e.g.,
2386 /// "std::vector" or "x->member", or as part of unqualified name lookup.
2388 /// Different lookup criteria can find different names. For example, a
2389 /// particular scope can have both a struct and a function of the same
2390 /// name, and each can be found by certain lookup criteria. For more
2391 /// information about lookup criteria, see the documentation for the
2392 /// class LookupCriteria.
2394 /// \param R captures both the lookup criteria and any lookup results found.
2396 /// \param LookupCtx The context in which qualified name lookup will
2397 /// search. If the lookup criteria permits, name lookup may also search
2398 /// in the parent contexts or (for C++ classes) base classes.
2400 /// \param InUnqualifiedLookup true if this is qualified name lookup that
2401 /// occurs as part of unqualified name lookup.
2403 /// \returns true if lookup succeeded, false if it failed.
2404 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2405 bool InUnqualifiedLookup) {
2406 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2408 if (!R.getLookupName())
2409 return false;
2411 // Make sure that the declaration context is complete.
2412 assert((!isa<TagDecl>(LookupCtx) ||
2413 LookupCtx->isDependentContext() ||
2414 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2415 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2416 "Declaration context must already be complete!");
2418 struct QualifiedLookupInScope {
2419 bool oldVal;
2420 DeclContext *Context;
2421 // Set flag in DeclContext informing debugger that we're looking for qualified name
2422 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2423 oldVal = ctx->setUseQualifiedLookup();
2425 ~QualifiedLookupInScope() {
2426 Context->setUseQualifiedLookup(oldVal);
2428 } QL(LookupCtx);
2430 if (LookupDirect(*this, R, LookupCtx)) {
2431 R.resolveKind();
2432 if (isa<CXXRecordDecl>(LookupCtx))
2433 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
2434 return true;
2437 // Don't descend into implied contexts for redeclarations.
2438 // C++98 [namespace.qual]p6:
2439 // In a declaration for a namespace member in which the
2440 // declarator-id is a qualified-id, given that the qualified-id
2441 // for the namespace member has the form
2442 // nested-name-specifier unqualified-id
2443 // the unqualified-id shall name a member of the namespace
2444 // designated by the nested-name-specifier.
2445 // See also [class.mfct]p5 and [class.static.data]p2.
2446 if (R.isForRedeclaration())
2447 return false;
2449 // If this is a namespace, look it up in the implied namespaces.
2450 if (LookupCtx->isFileContext())
2451 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2453 // If this isn't a C++ class, we aren't allowed to look into base
2454 // classes, we're done.
2455 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2456 if (!LookupRec || !LookupRec->getDefinition())
2457 return false;
2459 // We're done for lookups that can never succeed for C++ classes.
2460 if (R.getLookupKind() == LookupOperatorName ||
2461 R.getLookupKind() == LookupNamespaceName ||
2462 R.getLookupKind() == LookupObjCProtocolName ||
2463 R.getLookupKind() == LookupLabel)
2464 return false;
2466 // If we're performing qualified name lookup into a dependent class,
2467 // then we are actually looking into a current instantiation. If we have any
2468 // dependent base classes, then we either have to delay lookup until
2469 // template instantiation time (at which point all bases will be available)
2470 // or we have to fail.
2471 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2472 LookupRec->hasAnyDependentBases()) {
2473 R.setNotFoundInCurrentInstantiation();
2474 return false;
2477 // Perform lookup into our base classes.
2479 DeclarationName Name = R.getLookupName();
2480 unsigned IDNS = R.getIdentifierNamespace();
2482 // Look for this member in our base classes.
2483 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2484 CXXBasePath &Path) -> bool {
2485 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2486 // Drop leading non-matching lookup results from the declaration list so
2487 // we don't need to consider them again below.
2488 for (Path.Decls = BaseRecord->lookup(Name).begin();
2489 Path.Decls != Path.Decls.end(); ++Path.Decls) {
2490 if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2491 return true;
2493 return false;
2496 CXXBasePaths Paths;
2497 Paths.setOrigin(LookupRec);
2498 if (!LookupRec->lookupInBases(BaseCallback, Paths))
2499 return false;
2501 R.setNamingClass(LookupRec);
2503 // C++ [class.member.lookup]p2:
2504 // [...] If the resulting set of declarations are not all from
2505 // sub-objects of the same type, or the set has a nonstatic member
2506 // and includes members from distinct sub-objects, there is an
2507 // ambiguity and the program is ill-formed. Otherwise that set is
2508 // the result of the lookup.
2509 QualType SubobjectType;
2510 int SubobjectNumber = 0;
2511 AccessSpecifier SubobjectAccess = AS_none;
2513 // Check whether the given lookup result contains only static members.
2514 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2515 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2516 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2517 return false;
2518 return true;
2521 bool TemplateNameLookup = R.isTemplateNameLookup();
2523 // Determine whether two sets of members contain the same members, as
2524 // required by C++ [class.member.lookup]p6.
2525 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2526 DeclContext::lookup_iterator B) {
2527 using Iterator = DeclContextLookupResult::iterator;
2528 using Result = const void *;
2530 auto Next = [&](Iterator &It, Iterator End) -> Result {
2531 while (It != End) {
2532 NamedDecl *ND = *It++;
2533 if (!ND->isInIdentifierNamespace(IDNS))
2534 continue;
2536 // C++ [temp.local]p3:
2537 // A lookup that finds an injected-class-name (10.2) can result in
2538 // an ambiguity in certain cases (for example, if it is found in
2539 // more than one base class). If all of the injected-class-names
2540 // that are found refer to specializations of the same class
2541 // template, and if the name is used as a template-name, the
2542 // reference refers to the class template itself and not a
2543 // specialization thereof, and is not ambiguous.
2544 if (TemplateNameLookup)
2545 if (auto *TD = getAsTemplateNameDecl(ND))
2546 ND = TD;
2548 // C++ [class.member.lookup]p3:
2549 // type declarations (including injected-class-names) are replaced by
2550 // the types they designate
2551 if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {
2552 QualType T = Context.getTypeDeclType(TD);
2553 return T.getCanonicalType().getAsOpaquePtr();
2556 return ND->getUnderlyingDecl()->getCanonicalDecl();
2558 return nullptr;
2561 // We'll often find the declarations are in the same order. Handle this
2562 // case (and the special case of only one declaration) efficiently.
2563 Iterator AIt = A, BIt = B, AEnd, BEnd;
2564 while (true) {
2565 Result AResult = Next(AIt, AEnd);
2566 Result BResult = Next(BIt, BEnd);
2567 if (!AResult && !BResult)
2568 return true;
2569 if (!AResult || !BResult)
2570 return false;
2571 if (AResult != BResult) {
2572 // Found a mismatch; carefully check both lists, accounting for the
2573 // possibility of declarations appearing more than once.
2574 llvm::SmallDenseMap<Result, bool, 32> AResults;
2575 for (; AResult; AResult = Next(AIt, AEnd))
2576 AResults.insert({AResult, /*FoundInB*/false});
2577 unsigned Found = 0;
2578 for (; BResult; BResult = Next(BIt, BEnd)) {
2579 auto It = AResults.find(BResult);
2580 if (It == AResults.end())
2581 return false;
2582 if (!It->second) {
2583 It->second = true;
2584 ++Found;
2587 return AResults.size() == Found;
2592 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2593 Path != PathEnd; ++Path) {
2594 const CXXBasePathElement &PathElement = Path->back();
2596 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2597 // across all paths.
2598 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2600 // Determine whether we're looking at a distinct sub-object or not.
2601 if (SubobjectType.isNull()) {
2602 // This is the first subobject we've looked at. Record its type.
2603 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2604 SubobjectNumber = PathElement.SubobjectNumber;
2605 continue;
2608 if (SubobjectType !=
2609 Context.getCanonicalType(PathElement.Base->getType())) {
2610 // We found members of the given name in two subobjects of
2611 // different types. If the declaration sets aren't the same, this
2612 // lookup is ambiguous.
2614 // FIXME: The language rule says that this applies irrespective of
2615 // whether the sets contain only static members.
2616 if (HasOnlyStaticMembers(Path->Decls) &&
2617 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2618 continue;
2620 R.setAmbiguousBaseSubobjectTypes(Paths);
2621 return true;
2624 // FIXME: This language rule no longer exists. Checking for ambiguous base
2625 // subobjects should be done as part of formation of a class member access
2626 // expression (when converting the object parameter to the member's type).
2627 if (SubobjectNumber != PathElement.SubobjectNumber) {
2628 // We have a different subobject of the same type.
2630 // C++ [class.member.lookup]p5:
2631 // A static member, a nested type or an enumerator defined in
2632 // a base class T can unambiguously be found even if an object
2633 // has more than one base class subobject of type T.
2634 if (HasOnlyStaticMembers(Path->Decls))
2635 continue;
2637 // We have found a nonstatic member name in multiple, distinct
2638 // subobjects. Name lookup is ambiguous.
2639 R.setAmbiguousBaseSubobjects(Paths);
2640 return true;
2644 // Lookup in a base class succeeded; return these results.
2646 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2647 I != E; ++I) {
2648 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2649 (*I)->getAccess());
2650 if (NamedDecl *ND = R.getAcceptableDecl(*I))
2651 R.addDecl(ND, AS);
2653 R.resolveKind();
2654 return true;
2657 /// Performs qualified name lookup or special type of lookup for
2658 /// "__super::" scope specifier.
2660 /// This routine is a convenience overload meant to be called from contexts
2661 /// that need to perform a qualified name lookup with an optional C++ scope
2662 /// specifier that might require special kind of lookup.
2664 /// \param R captures both the lookup criteria and any lookup results found.
2666 /// \param LookupCtx The context in which qualified name lookup will
2667 /// search.
2669 /// \param SS An optional C++ scope-specifier.
2671 /// \returns true if lookup succeeded, false if it failed.
2672 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2673 CXXScopeSpec &SS) {
2674 auto *NNS = SS.getScopeRep();
2675 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2676 return LookupInSuper(R, NNS->getAsRecordDecl());
2677 else
2679 return LookupQualifiedName(R, LookupCtx);
2682 /// Performs name lookup for a name that was parsed in the
2683 /// source code, and may contain a C++ scope specifier.
2685 /// This routine is a convenience routine meant to be called from
2686 /// contexts that receive a name and an optional C++ scope specifier
2687 /// (e.g., "N::M::x"). It will then perform either qualified or
2688 /// unqualified name lookup (with LookupQualifiedName or LookupName,
2689 /// respectively) on the given name and return those results. It will
2690 /// perform a special type of lookup for "__super::" scope specifier.
2692 /// @param S The scope from which unqualified name lookup will
2693 /// begin.
2695 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
2697 /// @param EnteringContext Indicates whether we are going to enter the
2698 /// context of the scope-specifier SS (if present).
2700 /// @returns True if any decls were found (but possibly ambiguous)
2701 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2702 bool AllowBuiltinCreation, bool EnteringContext) {
2703 if (SS && SS->isInvalid()) {
2704 // When the scope specifier is invalid, don't even look for
2705 // anything.
2706 return false;
2709 if (SS && SS->isSet()) {
2710 NestedNameSpecifier *NNS = SS->getScopeRep();
2711 if (NNS->getKind() == NestedNameSpecifier::Super)
2712 return LookupInSuper(R, NNS->getAsRecordDecl());
2714 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2715 // We have resolved the scope specifier to a particular declaration
2716 // contex, and will perform name lookup in that context.
2717 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2718 return false;
2720 R.setContextRange(SS->getRange());
2721 return LookupQualifiedName(R, DC);
2724 // We could not resolve the scope specified to a specific declaration
2725 // context, which means that SS refers to an unknown specialization.
2726 // Name lookup can't find anything in this case.
2727 R.setNotFoundInCurrentInstantiation();
2728 R.setContextRange(SS->getRange());
2729 return false;
2732 // Perform unqualified name lookup starting in the given scope.
2733 return LookupName(R, S, AllowBuiltinCreation);
2736 /// Perform qualified name lookup into all base classes of the given
2737 /// class.
2739 /// \param R captures both the lookup criteria and any lookup results found.
2741 /// \param Class The context in which qualified name lookup will
2742 /// search. Name lookup will search in all base classes merging the results.
2744 /// @returns True if any decls were found (but possibly ambiguous)
2745 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2746 // The access-control rules we use here are essentially the rules for
2747 // doing a lookup in Class that just magically skipped the direct
2748 // members of Class itself. That is, the naming class is Class, and the
2749 // access includes the access of the base.
2750 for (const auto &BaseSpec : Class->bases()) {
2751 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2752 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2753 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2754 Result.setBaseObjectType(Context.getRecordType(Class));
2755 LookupQualifiedName(Result, RD);
2757 // Copy the lookup results into the target, merging the base's access into
2758 // the path access.
2759 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2760 R.addDecl(I.getDecl(),
2761 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2762 I.getAccess()));
2765 Result.suppressDiagnostics();
2768 R.resolveKind();
2769 R.setNamingClass(Class);
2771 return !R.empty();
2774 /// Produce a diagnostic describing the ambiguity that resulted
2775 /// from name lookup.
2777 /// \param Result The result of the ambiguous lookup to be diagnosed.
2778 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2779 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2781 DeclarationName Name = Result.getLookupName();
2782 SourceLocation NameLoc = Result.getNameLoc();
2783 SourceRange LookupRange = Result.getContextRange();
2785 switch (Result.getAmbiguityKind()) {
2786 case LookupResult::AmbiguousBaseSubobjects: {
2787 CXXBasePaths *Paths = Result.getBasePaths();
2788 QualType SubobjectType = Paths->front().back().Base->getType();
2789 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2790 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2791 << LookupRange;
2793 DeclContext::lookup_iterator Found = Paths->front().Decls;
2794 while (isa<CXXMethodDecl>(*Found) &&
2795 cast<CXXMethodDecl>(*Found)->isStatic())
2796 ++Found;
2798 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2799 break;
2802 case LookupResult::AmbiguousBaseSubobjectTypes: {
2803 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2804 << Name << LookupRange;
2806 CXXBasePaths *Paths = Result.getBasePaths();
2807 std::set<const NamedDecl *> DeclsPrinted;
2808 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2809 PathEnd = Paths->end();
2810 Path != PathEnd; ++Path) {
2811 const NamedDecl *D = *Path->Decls;
2812 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2813 continue;
2814 if (DeclsPrinted.insert(D).second) {
2815 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2816 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2817 << TD->getUnderlyingType();
2818 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2819 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2820 << Context.getTypeDeclType(TD);
2821 else
2822 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2825 break;
2828 case LookupResult::AmbiguousTagHiding: {
2829 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2831 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2833 for (auto *D : Result)
2834 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2835 TagDecls.insert(TD);
2836 Diag(TD->getLocation(), diag::note_hidden_tag);
2839 for (auto *D : Result)
2840 if (!isa<TagDecl>(D))
2841 Diag(D->getLocation(), diag::note_hiding_object);
2843 // For recovery purposes, go ahead and implement the hiding.
2844 LookupResult::Filter F = Result.makeFilter();
2845 while (F.hasNext()) {
2846 if (TagDecls.count(F.next()))
2847 F.erase();
2849 F.done();
2850 break;
2853 case LookupResult::AmbiguousReference: {
2854 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2856 for (auto *D : Result)
2857 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2858 break;
2863 namespace {
2864 struct AssociatedLookup {
2865 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2866 Sema::AssociatedNamespaceSet &Namespaces,
2867 Sema::AssociatedClassSet &Classes)
2868 : S(S), Namespaces(Namespaces), Classes(Classes),
2869 InstantiationLoc(InstantiationLoc) {
2872 bool addClassTransitive(CXXRecordDecl *RD) {
2873 Classes.insert(RD);
2874 return ClassesTransitive.insert(RD);
2877 Sema &S;
2878 Sema::AssociatedNamespaceSet &Namespaces;
2879 Sema::AssociatedClassSet &Classes;
2880 SourceLocation InstantiationLoc;
2882 private:
2883 Sema::AssociatedClassSet ClassesTransitive;
2885 } // end anonymous namespace
2887 static void
2888 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2890 // Given the declaration context \param Ctx of a class, class template or
2891 // enumeration, add the associated namespaces to \param Namespaces as described
2892 // in [basic.lookup.argdep]p2.
2893 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2894 DeclContext *Ctx) {
2895 // The exact wording has been changed in C++14 as a result of
2896 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2897 // to all language versions since it is possible to return a local type
2898 // from a lambda in C++11.
2900 // C++14 [basic.lookup.argdep]p2:
2901 // If T is a class type [...]. Its associated namespaces are the innermost
2902 // enclosing namespaces of its associated classes. [...]
2904 // If T is an enumeration type, its associated namespace is the innermost
2905 // enclosing namespace of its declaration. [...]
2907 // We additionally skip inline namespaces. The innermost non-inline namespace
2908 // contains all names of all its nested inline namespaces anyway, so we can
2909 // replace the entire inline namespace tree with its root.
2910 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2911 Ctx = Ctx->getParent();
2913 Namespaces.insert(Ctx->getPrimaryContext());
2916 // Add the associated classes and namespaces for argument-dependent
2917 // lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2918 static void
2919 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2920 const TemplateArgument &Arg) {
2921 // C++ [basic.lookup.argdep]p2, last bullet:
2922 // -- [...] ;
2923 switch (Arg.getKind()) {
2924 case TemplateArgument::Null:
2925 break;
2927 case TemplateArgument::Type:
2928 // [...] the namespaces and classes associated with the types of the
2929 // template arguments provided for template type parameters (excluding
2930 // template template parameters)
2931 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
2932 break;
2934 case TemplateArgument::Template:
2935 case TemplateArgument::TemplateExpansion: {
2936 // [...] the namespaces in which any template template arguments are
2937 // defined; and the classes in which any member templates used as
2938 // template template arguments are defined.
2939 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2940 if (ClassTemplateDecl *ClassTemplate
2941 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2942 DeclContext *Ctx = ClassTemplate->getDeclContext();
2943 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2944 Result.Classes.insert(EnclosingClass);
2945 // Add the associated namespace for this class.
2946 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2948 break;
2951 case TemplateArgument::Declaration:
2952 case TemplateArgument::Integral:
2953 case TemplateArgument::Expression:
2954 case TemplateArgument::NullPtr:
2955 // [Note: non-type template arguments do not contribute to the set of
2956 // associated namespaces. ]
2957 break;
2959 case TemplateArgument::Pack:
2960 for (const auto &P : Arg.pack_elements())
2961 addAssociatedClassesAndNamespaces(Result, P);
2962 break;
2966 // Add the associated classes and namespaces for argument-dependent lookup
2967 // with an argument of class type (C++ [basic.lookup.argdep]p2).
2968 static void
2969 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2970 CXXRecordDecl *Class) {
2972 // Just silently ignore anything whose name is __va_list_tag.
2973 if (Class->getDeclName() == Result.S.VAListTagName)
2974 return;
2976 // C++ [basic.lookup.argdep]p2:
2977 // [...]
2978 // -- If T is a class type (including unions), its associated
2979 // classes are: the class itself; the class of which it is a
2980 // member, if any; and its direct and indirect base classes.
2981 // Its associated namespaces are the innermost enclosing
2982 // namespaces of its associated classes.
2984 // Add the class of which it is a member, if any.
2985 DeclContext *Ctx = Class->getDeclContext();
2986 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2987 Result.Classes.insert(EnclosingClass);
2989 // Add the associated namespace for this class.
2990 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2992 // -- If T is a template-id, its associated namespaces and classes are
2993 // the namespace in which the template is defined; for member
2994 // templates, the member template's class; the namespaces and classes
2995 // associated with the types of the template arguments provided for
2996 // template type parameters (excluding template template parameters); the
2997 // namespaces in which any template template arguments are defined; and
2998 // the classes in which any member templates used as template template
2999 // arguments are defined. [Note: non-type template arguments do not
3000 // contribute to the set of associated namespaces. ]
3001 if (ClassTemplateSpecializationDecl *Spec
3002 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
3003 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
3004 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3005 Result.Classes.insert(EnclosingClass);
3006 // Add the associated namespace for this class.
3007 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3009 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3010 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3011 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
3014 // Add the class itself. If we've already transitively visited this class,
3015 // we don't need to visit base classes.
3016 if (!Result.addClassTransitive(Class))
3017 return;
3019 // Only recurse into base classes for complete types.
3020 if (!Result.S.isCompleteType(Result.InstantiationLoc,
3021 Result.S.Context.getRecordType(Class)))
3022 return;
3024 // Add direct and indirect base classes along with their associated
3025 // namespaces.
3026 SmallVector<CXXRecordDecl *, 32> Bases;
3027 Bases.push_back(Class);
3028 while (!Bases.empty()) {
3029 // Pop this class off the stack.
3030 Class = Bases.pop_back_val();
3032 // Visit the base classes.
3033 for (const auto &Base : Class->bases()) {
3034 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
3035 // In dependent contexts, we do ADL twice, and the first time around,
3036 // the base type might be a dependent TemplateSpecializationType, or a
3037 // TemplateTypeParmType. If that happens, simply ignore it.
3038 // FIXME: If we want to support export, we probably need to add the
3039 // namespace of the template in a TemplateSpecializationType, or even
3040 // the classes and namespaces of known non-dependent arguments.
3041 if (!BaseType)
3042 continue;
3043 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3044 if (Result.addClassTransitive(BaseDecl)) {
3045 // Find the associated namespace for this base class.
3046 DeclContext *BaseCtx = BaseDecl->getDeclContext();
3047 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
3049 // Make sure we visit the bases of this base class.
3050 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
3051 Bases.push_back(BaseDecl);
3057 // Add the associated classes and namespaces for
3058 // argument-dependent lookup with an argument of type T
3059 // (C++ [basic.lookup.koenig]p2).
3060 static void
3061 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
3062 // C++ [basic.lookup.koenig]p2:
3064 // For each argument type T in the function call, there is a set
3065 // of zero or more associated namespaces and a set of zero or more
3066 // associated classes to be considered. The sets of namespaces and
3067 // classes is determined entirely by the types of the function
3068 // arguments (and the namespace of any template template
3069 // argument). Typedef names and using-declarations used to specify
3070 // the types do not contribute to this set. The sets of namespaces
3071 // and classes are determined in the following way:
3073 SmallVector<const Type *, 16> Queue;
3074 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
3076 while (true) {
3077 switch (T->getTypeClass()) {
3079 #define TYPE(Class, Base)
3080 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3081 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3082 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3083 #define ABSTRACT_TYPE(Class, Base)
3084 #include "clang/AST/TypeNodes.inc"
3085 // T is canonical. We can also ignore dependent types because
3086 // we don't need to do ADL at the definition point, but if we
3087 // wanted to implement template export (or if we find some other
3088 // use for associated classes and namespaces...) this would be
3089 // wrong.
3090 break;
3092 // -- If T is a pointer to U or an array of U, its associated
3093 // namespaces and classes are those associated with U.
3094 case Type::Pointer:
3095 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
3096 continue;
3097 case Type::ConstantArray:
3098 case Type::IncompleteArray:
3099 case Type::VariableArray:
3100 T = cast<ArrayType>(T)->getElementType().getTypePtr();
3101 continue;
3103 // -- If T is a fundamental type, its associated sets of
3104 // namespaces and classes are both empty.
3105 case Type::Builtin:
3106 break;
3108 // -- If T is a class type (including unions), its associated
3109 // classes are: the class itself; the class of which it is
3110 // a member, if any; and its direct and indirect base classes.
3111 // Its associated namespaces are the innermost enclosing
3112 // namespaces of its associated classes.
3113 case Type::Record: {
3114 CXXRecordDecl *Class =
3115 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
3116 addAssociatedClassesAndNamespaces(Result, Class);
3117 break;
3120 // -- If T is an enumeration type, its associated namespace
3121 // is the innermost enclosing namespace of its declaration.
3122 // If it is a class member, its associated class is the
3123 // member’s class; else it has no associated class.
3124 case Type::Enum: {
3125 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
3127 DeclContext *Ctx = Enum->getDeclContext();
3128 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3129 Result.Classes.insert(EnclosingClass);
3131 // Add the associated namespace for this enumeration.
3132 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3134 break;
3137 // -- If T is a function type, its associated namespaces and
3138 // classes are those associated with the function parameter
3139 // types and those associated with the return type.
3140 case Type::FunctionProto: {
3141 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
3142 for (const auto &Arg : Proto->param_types())
3143 Queue.push_back(Arg.getTypePtr());
3144 // fallthrough
3145 [[fallthrough]];
3147 case Type::FunctionNoProto: {
3148 const FunctionType *FnType = cast<FunctionType>(T);
3149 T = FnType->getReturnType().getTypePtr();
3150 continue;
3153 // -- If T is a pointer to a member function of a class X, its
3154 // associated namespaces and classes are those associated
3155 // with the function parameter types and return type,
3156 // together with those associated with X.
3158 // -- If T is a pointer to a data member of class X, its
3159 // associated namespaces and classes are those associated
3160 // with the member type together with those associated with
3161 // X.
3162 case Type::MemberPointer: {
3163 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
3165 // Queue up the class type into which this points.
3166 Queue.push_back(MemberPtr->getClass());
3168 // And directly continue with the pointee type.
3169 T = MemberPtr->getPointeeType().getTypePtr();
3170 continue;
3173 // As an extension, treat this like a normal pointer.
3174 case Type::BlockPointer:
3175 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
3176 continue;
3178 // References aren't covered by the standard, but that's such an
3179 // obvious defect that we cover them anyway.
3180 case Type::LValueReference:
3181 case Type::RValueReference:
3182 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
3183 continue;
3185 // These are fundamental types.
3186 case Type::Vector:
3187 case Type::ExtVector:
3188 case Type::ConstantMatrix:
3189 case Type::Complex:
3190 case Type::BitInt:
3191 break;
3193 // Non-deduced auto types only get here for error cases.
3194 case Type::Auto:
3195 case Type::DeducedTemplateSpecialization:
3196 break;
3198 // If T is an Objective-C object or interface type, or a pointer to an
3199 // object or interface type, the associated namespace is the global
3200 // namespace.
3201 case Type::ObjCObject:
3202 case Type::ObjCInterface:
3203 case Type::ObjCObjectPointer:
3204 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
3205 break;
3207 // Atomic types are just wrappers; use the associations of the
3208 // contained type.
3209 case Type::Atomic:
3210 T = cast<AtomicType>(T)->getValueType().getTypePtr();
3211 continue;
3212 case Type::Pipe:
3213 T = cast<PipeType>(T)->getElementType().getTypePtr();
3214 continue;
3217 if (Queue.empty())
3218 break;
3219 T = Queue.pop_back_val();
3223 /// Find the associated classes and namespaces for
3224 /// argument-dependent lookup for a call with the given set of
3225 /// arguments.
3227 /// This routine computes the sets of associated classes and associated
3228 /// namespaces searched by argument-dependent lookup
3229 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
3230 void Sema::FindAssociatedClassesAndNamespaces(
3231 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
3232 AssociatedNamespaceSet &AssociatedNamespaces,
3233 AssociatedClassSet &AssociatedClasses) {
3234 AssociatedNamespaces.clear();
3235 AssociatedClasses.clear();
3237 AssociatedLookup Result(*this, InstantiationLoc,
3238 AssociatedNamespaces, AssociatedClasses);
3240 // C++ [basic.lookup.koenig]p2:
3241 // For each argument type T in the function call, there is a set
3242 // of zero or more associated namespaces and a set of zero or more
3243 // associated classes to be considered. The sets of namespaces and
3244 // classes is determined entirely by the types of the function
3245 // arguments (and the namespace of any template template
3246 // argument).
3247 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3248 Expr *Arg = Args[ArgIdx];
3250 if (Arg->getType() != Context.OverloadTy) {
3251 addAssociatedClassesAndNamespaces(Result, Arg->getType());
3252 continue;
3255 // [...] In addition, if the argument is the name or address of a
3256 // set of overloaded functions and/or function templates, its
3257 // associated classes and namespaces are the union of those
3258 // associated with each of the members of the set: the namespace
3259 // in which the function or function template is defined and the
3260 // classes and namespaces associated with its (non-dependent)
3261 // parameter types and return type.
3262 OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
3264 for (const NamedDecl *D : OE->decls()) {
3265 // Look through any using declarations to find the underlying function.
3266 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
3268 // Add the classes and namespaces associated with the parameter
3269 // types and return type of this function.
3270 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
3275 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
3276 SourceLocation Loc,
3277 LookupNameKind NameKind,
3278 RedeclarationKind Redecl) {
3279 LookupResult R(*this, Name, Loc, NameKind, Redecl);
3280 LookupName(R, S);
3281 return R.getAsSingle<NamedDecl>();
3284 /// Find the protocol with the given name, if any.
3285 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
3286 SourceLocation IdLoc,
3287 RedeclarationKind Redecl) {
3288 Decl *D = LookupSingleName(TUScope, II, IdLoc,
3289 LookupObjCProtocolName, Redecl);
3290 return cast_or_null<ObjCProtocolDecl>(D);
3293 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3294 UnresolvedSetImpl &Functions) {
3295 // C++ [over.match.oper]p3:
3296 // -- The set of non-member candidates is the result of the
3297 // unqualified lookup of operator@ in the context of the
3298 // expression according to the usual rules for name lookup in
3299 // unqualified function calls (3.4.2) except that all member
3300 // functions are ignored.
3301 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3302 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3303 LookupName(Operators, S);
3305 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3306 Functions.append(Operators.begin(), Operators.end());
3309 Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
3310 CXXSpecialMember SM,
3311 bool ConstArg,
3312 bool VolatileArg,
3313 bool RValueThis,
3314 bool ConstThis,
3315 bool VolatileThis) {
3316 assert(CanDeclareSpecialMemberFunction(RD) &&
3317 "doing special member lookup into record that isn't fully complete");
3318 RD = RD->getDefinition();
3319 if (RValueThis || ConstThis || VolatileThis)
3320 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
3321 "constructors and destructors always have unqualified lvalue this");
3322 if (ConstArg || VolatileArg)
3323 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
3324 "parameter-less special members can't have qualified arguments");
3326 // FIXME: Get the caller to pass in a location for the lookup.
3327 SourceLocation LookupLoc = RD->getLocation();
3329 llvm::FoldingSetNodeID ID;
3330 ID.AddPointer(RD);
3331 ID.AddInteger(SM);
3332 ID.AddInteger(ConstArg);
3333 ID.AddInteger(VolatileArg);
3334 ID.AddInteger(RValueThis);
3335 ID.AddInteger(ConstThis);
3336 ID.AddInteger(VolatileThis);
3338 void *InsertPoint;
3339 SpecialMemberOverloadResultEntry *Result =
3340 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3342 // This was already cached
3343 if (Result)
3344 return *Result;
3346 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
3347 Result = new (Result) SpecialMemberOverloadResultEntry(ID);
3348 SpecialMemberCache.InsertNode(Result, InsertPoint);
3350 if (SM == CXXDestructor) {
3351 if (RD->needsImplicitDestructor()) {
3352 runWithSufficientStackSpace(RD->getLocation(), [&] {
3353 DeclareImplicitDestructor(RD);
3356 CXXDestructorDecl *DD = RD->getDestructor();
3357 Result->setMethod(DD);
3358 Result->setKind(DD && !DD->isDeleted()
3359 ? SpecialMemberOverloadResult::Success
3360 : SpecialMemberOverloadResult::NoMemberOrDeleted);
3361 return *Result;
3364 // Prepare for overload resolution. Here we construct a synthetic argument
3365 // if necessary and make sure that implicit functions are declared.
3366 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
3367 DeclarationName Name;
3368 Expr *Arg = nullptr;
3369 unsigned NumArgs;
3371 QualType ArgType = CanTy;
3372 ExprValueKind VK = VK_LValue;
3374 if (SM == CXXDefaultConstructor) {
3375 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3376 NumArgs = 0;
3377 if (RD->needsImplicitDefaultConstructor()) {
3378 runWithSufficientStackSpace(RD->getLocation(), [&] {
3379 DeclareImplicitDefaultConstructor(RD);
3382 } else {
3383 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
3384 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3385 if (RD->needsImplicitCopyConstructor()) {
3386 runWithSufficientStackSpace(RD->getLocation(), [&] {
3387 DeclareImplicitCopyConstructor(RD);
3390 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {
3391 runWithSufficientStackSpace(RD->getLocation(), [&] {
3392 DeclareImplicitMoveConstructor(RD);
3395 } else {
3396 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3397 if (RD->needsImplicitCopyAssignment()) {
3398 runWithSufficientStackSpace(RD->getLocation(), [&] {
3399 DeclareImplicitCopyAssignment(RD);
3402 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {
3403 runWithSufficientStackSpace(RD->getLocation(), [&] {
3404 DeclareImplicitMoveAssignment(RD);
3409 if (ConstArg)
3410 ArgType.addConst();
3411 if (VolatileArg)
3412 ArgType.addVolatile();
3414 // This isn't /really/ specified by the standard, but it's implied
3415 // we should be working from a PRValue in the case of move to ensure
3416 // that we prefer to bind to rvalue references, and an LValue in the
3417 // case of copy to ensure we don't bind to rvalue references.
3418 // Possibly an XValue is actually correct in the case of move, but
3419 // there is no semantic difference for class types in this restricted
3420 // case.
3421 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
3422 VK = VK_LValue;
3423 else
3424 VK = VK_PRValue;
3427 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3429 if (SM != CXXDefaultConstructor) {
3430 NumArgs = 1;
3431 Arg = &FakeArg;
3434 // Create the object argument
3435 QualType ThisTy = CanTy;
3436 if (ConstThis)
3437 ThisTy.addConst();
3438 if (VolatileThis)
3439 ThisTy.addVolatile();
3440 Expr::Classification Classification =
3441 OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
3442 .Classify(Context);
3444 // Now we perform lookup on the name we computed earlier and do overload
3445 // resolution. Lookup is only performed directly into the class since there
3446 // will always be a (possibly implicit) declaration to shadow any others.
3447 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
3448 DeclContext::lookup_result R = RD->lookup(Name);
3450 if (R.empty()) {
3451 // We might have no default constructor because we have a lambda's closure
3452 // type, rather than because there's some other declared constructor.
3453 // Every class has a copy/move constructor, copy/move assignment, and
3454 // destructor.
3455 assert(SM == CXXDefaultConstructor &&
3456 "lookup for a constructor or assignment operator was empty");
3457 Result->setMethod(nullptr);
3458 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3459 return *Result;
3462 // Copy the candidates as our processing of them may load new declarations
3463 // from an external source and invalidate lookup_result.
3464 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3466 for (NamedDecl *CandDecl : Candidates) {
3467 if (CandDecl->isInvalidDecl())
3468 continue;
3470 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
3471 auto CtorInfo = getConstructorInfo(Cand);
3472 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3473 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3474 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3475 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3476 else if (CtorInfo)
3477 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3478 llvm::makeArrayRef(&Arg, NumArgs), OCS,
3479 /*SuppressUserConversions*/ true);
3480 else
3481 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3482 /*SuppressUserConversions*/ true);
3483 } else if (FunctionTemplateDecl *Tmpl =
3484 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3485 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3486 AddMethodTemplateCandidate(
3487 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
3488 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3489 else if (CtorInfo)
3490 AddTemplateOverloadCandidate(
3491 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3492 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3493 else
3494 AddTemplateOverloadCandidate(
3495 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3496 } else {
3497 assert(isa<UsingDecl>(Cand.getDecl()) &&
3498 "illegal Kind of operator = Decl");
3502 OverloadCandidateSet::iterator Best;
3503 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3504 case OR_Success:
3505 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3506 Result->setKind(SpecialMemberOverloadResult::Success);
3507 break;
3509 case OR_Deleted:
3510 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3511 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3512 break;
3514 case OR_Ambiguous:
3515 Result->setMethod(nullptr);
3516 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3517 break;
3519 case OR_No_Viable_Function:
3520 Result->setMethod(nullptr);
3521 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3522 break;
3525 return *Result;
3528 /// Look up the default constructor for the given class.
3529 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
3530 SpecialMemberOverloadResult Result =
3531 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3532 false, false);
3534 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3537 /// Look up the copying constructor for the given class.
3538 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
3539 unsigned Quals) {
3540 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3541 "non-const, non-volatile qualifiers for copy ctor arg");
3542 SpecialMemberOverloadResult Result =
3543 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3544 Quals & Qualifiers::Volatile, false, false, false);
3546 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3549 /// Look up the moving constructor for the given class.
3550 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3551 unsigned Quals) {
3552 SpecialMemberOverloadResult Result =
3553 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3554 Quals & Qualifiers::Volatile, false, false, false);
3556 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3559 /// Look up the constructors for the given class.
3560 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
3561 // If the implicit constructors have not yet been declared, do so now.
3562 if (CanDeclareSpecialMemberFunction(Class)) {
3563 runWithSufficientStackSpace(Class->getLocation(), [&] {
3564 if (Class->needsImplicitDefaultConstructor())
3565 DeclareImplicitDefaultConstructor(Class);
3566 if (Class->needsImplicitCopyConstructor())
3567 DeclareImplicitCopyConstructor(Class);
3568 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3569 DeclareImplicitMoveConstructor(Class);
3573 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3574 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3575 return Class->lookup(Name);
3578 /// Look up the copying assignment operator for the given class.
3579 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3580 unsigned Quals, bool RValueThis,
3581 unsigned ThisQuals) {
3582 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3583 "non-const, non-volatile qualifiers for copy assignment arg");
3584 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3585 "non-const, non-volatile qualifiers for copy assignment this");
3586 SpecialMemberOverloadResult Result =
3587 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3588 Quals & Qualifiers::Volatile, RValueThis,
3589 ThisQuals & Qualifiers::Const,
3590 ThisQuals & Qualifiers::Volatile);
3592 return Result.getMethod();
3595 /// Look up the moving assignment operator for the given class.
3596 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
3597 unsigned Quals,
3598 bool RValueThis,
3599 unsigned ThisQuals) {
3600 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3601 "non-const, non-volatile qualifiers for copy assignment this");
3602 SpecialMemberOverloadResult Result =
3603 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3604 Quals & Qualifiers::Volatile, RValueThis,
3605 ThisQuals & Qualifiers::Const,
3606 ThisQuals & Qualifiers::Volatile);
3608 return Result.getMethod();
3611 /// Look for the destructor of the given class.
3613 /// During semantic analysis, this routine should be used in lieu of
3614 /// CXXRecordDecl::getDestructor().
3616 /// \returns The destructor for this class.
3617 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
3618 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3619 false, false, false,
3620 false, false).getMethod());
3623 /// LookupLiteralOperator - Determine which literal operator should be used for
3624 /// a user-defined literal, per C++11 [lex.ext].
3626 /// Normal overload resolution is not used to select which literal operator to
3627 /// call for a user-defined literal. Look up the provided literal operator name,
3628 /// and filter the results to the appropriate set for the given argument types.
3629 Sema::LiteralOperatorLookupResult
3630 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3631 ArrayRef<QualType> ArgTys, bool AllowRaw,
3632 bool AllowTemplate, bool AllowStringTemplatePack,
3633 bool DiagnoseMissing, StringLiteral *StringLit) {
3634 LookupName(R, S);
3635 assert(R.getResultKind() != LookupResult::Ambiguous &&
3636 "literal operator lookup can't be ambiguous");
3638 // Filter the lookup results appropriately.
3639 LookupResult::Filter F = R.makeFilter();
3641 bool AllowCooked = true;
3642 bool FoundRaw = false;
3643 bool FoundTemplate = false;
3644 bool FoundStringTemplatePack = false;
3645 bool FoundCooked = false;
3647 while (F.hasNext()) {
3648 Decl *D = F.next();
3649 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3650 D = USD->getTargetDecl();
3652 // If the declaration we found is invalid, skip it.
3653 if (D->isInvalidDecl()) {
3654 F.erase();
3655 continue;
3658 bool IsRaw = false;
3659 bool IsTemplate = false;
3660 bool IsStringTemplatePack = false;
3661 bool IsCooked = false;
3663 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3664 if (FD->getNumParams() == 1 &&
3665 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3666 IsRaw = true;
3667 else if (FD->getNumParams() == ArgTys.size()) {
3668 IsCooked = true;
3669 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3670 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3671 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3672 IsCooked = false;
3673 break;
3678 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3679 TemplateParameterList *Params = FD->getTemplateParameters();
3680 if (Params->size() == 1) {
3681 IsTemplate = true;
3682 if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
3683 // Implied but not stated: user-defined integer and floating literals
3684 // only ever use numeric literal operator templates, not templates
3685 // taking a parameter of class type.
3686 F.erase();
3687 continue;
3690 // A string literal template is only considered if the string literal
3691 // is a well-formed template argument for the template parameter.
3692 if (StringLit) {
3693 SFINAETrap Trap(*this);
3694 SmallVector<TemplateArgument, 1> Checked;
3695 TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);
3696 if (CheckTemplateArgument(Params->getParam(0), Arg, FD,
3697 R.getNameLoc(), R.getNameLoc(), 0,
3698 Checked) ||
3699 Trap.hasErrorOccurred())
3700 IsTemplate = false;
3702 } else {
3703 IsStringTemplatePack = true;
3707 if (AllowTemplate && StringLit && IsTemplate) {
3708 FoundTemplate = true;
3709 AllowRaw = false;
3710 AllowCooked = false;
3711 AllowStringTemplatePack = false;
3712 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3713 F.restart();
3714 FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3716 } else if (AllowCooked && IsCooked) {
3717 FoundCooked = true;
3718 AllowRaw = false;
3719 AllowTemplate = StringLit;
3720 AllowStringTemplatePack = false;
3721 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3722 // Go through again and remove the raw and template decls we've
3723 // already found.
3724 F.restart();
3725 FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3727 } else if (AllowRaw && IsRaw) {
3728 FoundRaw = true;
3729 } else if (AllowTemplate && IsTemplate) {
3730 FoundTemplate = true;
3731 } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3732 FoundStringTemplatePack = true;
3733 } else {
3734 F.erase();
3738 F.done();
3740 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3741 // form for string literal operator templates.
3742 if (StringLit && FoundTemplate)
3743 return LOLR_Template;
3745 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3746 // parameter type, that is used in preference to a raw literal operator
3747 // or literal operator template.
3748 if (FoundCooked)
3749 return LOLR_Cooked;
3751 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3752 // operator template, but not both.
3753 if (FoundRaw && FoundTemplate) {
3754 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3755 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3756 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
3757 return LOLR_Error;
3760 if (FoundRaw)
3761 return LOLR_Raw;
3763 if (FoundTemplate)
3764 return LOLR_Template;
3766 if (FoundStringTemplatePack)
3767 return LOLR_StringTemplatePack;
3769 // Didn't find anything we could use.
3770 if (DiagnoseMissing) {
3771 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3772 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3773 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3774 << (AllowTemplate || AllowStringTemplatePack);
3775 return LOLR_Error;
3778 return LOLR_ErrorNoDiagnostic;
3781 void ADLResult::insert(NamedDecl *New) {
3782 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3784 // If we haven't yet seen a decl for this key, or the last decl
3785 // was exactly this one, we're done.
3786 if (Old == nullptr || Old == New) {
3787 Old = New;
3788 return;
3791 // Otherwise, decide which is a more recent redeclaration.
3792 FunctionDecl *OldFD = Old->getAsFunction();
3793 FunctionDecl *NewFD = New->getAsFunction();
3795 FunctionDecl *Cursor = NewFD;
3796 while (true) {
3797 Cursor = Cursor->getPreviousDecl();
3799 // If we got to the end without finding OldFD, OldFD is the newer
3800 // declaration; leave things as they are.
3801 if (!Cursor) return;
3803 // If we do find OldFD, then NewFD is newer.
3804 if (Cursor == OldFD) break;
3806 // Otherwise, keep looking.
3809 Old = New;
3812 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3813 ArrayRef<Expr *> Args, ADLResult &Result) {
3814 // Find all of the associated namespaces and classes based on the
3815 // arguments we have.
3816 AssociatedNamespaceSet AssociatedNamespaces;
3817 AssociatedClassSet AssociatedClasses;
3818 FindAssociatedClassesAndNamespaces(Loc, Args,
3819 AssociatedNamespaces,
3820 AssociatedClasses);
3822 // C++ [basic.lookup.argdep]p3:
3823 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3824 // and let Y be the lookup set produced by argument dependent
3825 // lookup (defined as follows). If X contains [...] then Y is
3826 // empty. Otherwise Y is the set of declarations found in the
3827 // namespaces associated with the argument types as described
3828 // below. The set of declarations found by the lookup of the name
3829 // is the union of X and Y.
3831 // Here, we compute Y and add its members to the overloaded
3832 // candidate set.
3833 for (auto *NS : AssociatedNamespaces) {
3834 // When considering an associated namespace, the lookup is the
3835 // same as the lookup performed when the associated namespace is
3836 // used as a qualifier (3.4.3.2) except that:
3838 // -- Any using-directives in the associated namespace are
3839 // ignored.
3841 // -- Any namespace-scope friend functions declared in
3842 // associated classes are visible within their respective
3843 // namespaces even if they are not visible during an ordinary
3844 // lookup (11.4).
3846 // C++20 [basic.lookup.argdep] p4.3
3847 // -- are exported, are attached to a named module M, do not appear
3848 // in the translation unit containing the point of the lookup, and
3849 // have the same innermost enclosing non-inline namespace scope as
3850 // a declaration of an associated entity attached to M.
3851 DeclContext::lookup_result R = NS->lookup(Name);
3852 for (auto *D : R) {
3853 auto *Underlying = D;
3854 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3855 Underlying = USD->getTargetDecl();
3857 if (!isa<FunctionDecl>(Underlying) &&
3858 !isa<FunctionTemplateDecl>(Underlying))
3859 continue;
3861 // The declaration is visible to argument-dependent lookup if either
3862 // it's ordinarily visible or declared as a friend in an associated
3863 // class.
3864 bool Visible = false;
3865 for (D = D->getMostRecentDecl(); D;
3866 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3867 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
3868 if (isVisible(D)) {
3869 Visible = true;
3870 break;
3871 } else if (getLangOpts().CPlusPlusModules &&
3872 D->isInExportDeclContext()) {
3873 // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
3874 Module *FM = D->getOwningModule();
3875 // exports are only valid in module purview and outside of any
3876 // PMF (although a PMF should not even be present in a module
3877 // with an import).
3878 assert(FM && FM->isModulePurview() && !FM->isPrivateModule() &&
3879 "bad export context");
3880 // .. are attached to a named module M, do not appear in the
3881 // translation unit containing the point of the lookup..
3882 if (!isModuleUnitOfCurrentTU(FM) &&
3883 llvm::any_of(AssociatedClasses, [&](auto *E) {
3884 // ... and have the same innermost enclosing non-inline
3885 // namespace scope as a declaration of an associated entity
3886 // attached to M
3887 if (!E->hasOwningModule() ||
3888 E->getOwningModule()->getTopLevelModuleName() !=
3889 FM->getTopLevelModuleName())
3890 return false;
3891 // TODO: maybe this could be cached when generating the
3892 // associated namespaces / entities.
3893 DeclContext *Ctx = E->getDeclContext();
3894 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
3895 Ctx = Ctx->getParent();
3896 return Ctx == NS;
3897 })) {
3898 Visible = true;
3899 break;
3902 } else if (D->getFriendObjectKind()) {
3903 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3904 // [basic.lookup.argdep]p4:
3905 // Argument-dependent lookup finds all declarations of functions and
3906 // function templates that
3907 // - ...
3908 // - are declared as a friend ([class.friend]) of any class with a
3909 // reachable definition in the set of associated entities,
3911 // FIXME: If there's a merged definition of D that is reachable, then
3912 // the friend declaration should be considered.
3913 if (AssociatedClasses.count(RD) && isReachable(D)) {
3914 Visible = true;
3915 break;
3920 // FIXME: Preserve D as the FoundDecl.
3921 if (Visible)
3922 Result.insert(Underlying);
3927 //----------------------------------------------------------------------------
3928 // Search for all visible declarations.
3929 //----------------------------------------------------------------------------
3930 VisibleDeclConsumer::~VisibleDeclConsumer() { }
3932 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3934 namespace {
3936 class ShadowContextRAII;
3938 class VisibleDeclsRecord {
3939 public:
3940 /// An entry in the shadow map, which is optimized to store a
3941 /// single declaration (the common case) but can also store a list
3942 /// of declarations.
3943 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3945 private:
3946 /// A mapping from declaration names to the declarations that have
3947 /// this name within a particular scope.
3948 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3950 /// A list of shadow maps, which is used to model name hiding.
3951 std::list<ShadowMap> ShadowMaps;
3953 /// The declaration contexts we have already visited.
3954 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3956 friend class ShadowContextRAII;
3958 public:
3959 /// Determine whether we have already visited this context
3960 /// (and, if not, note that we are going to visit that context now).
3961 bool visitedContext(DeclContext *Ctx) {
3962 return !VisitedContexts.insert(Ctx).second;
3965 bool alreadyVisitedContext(DeclContext *Ctx) {
3966 return VisitedContexts.count(Ctx);
3969 /// Determine whether the given declaration is hidden in the
3970 /// current scope.
3972 /// \returns the declaration that hides the given declaration, or
3973 /// NULL if no such declaration exists.
3974 NamedDecl *checkHidden(NamedDecl *ND);
3976 /// Add a declaration to the current shadow map.
3977 void add(NamedDecl *ND) {
3978 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3982 /// RAII object that records when we've entered a shadow context.
3983 class ShadowContextRAII {
3984 VisibleDeclsRecord &Visible;
3986 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3988 public:
3989 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3990 Visible.ShadowMaps.emplace_back();
3993 ~ShadowContextRAII() {
3994 Visible.ShadowMaps.pop_back();
3998 } // end anonymous namespace
4000 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
4001 unsigned IDNS = ND->getIdentifierNamespace();
4002 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
4003 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
4004 SM != SMEnd; ++SM) {
4005 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
4006 if (Pos == SM->end())
4007 continue;
4009 for (auto *D : Pos->second) {
4010 // A tag declaration does not hide a non-tag declaration.
4011 if (D->hasTagIdentifierNamespace() &&
4012 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
4013 Decl::IDNS_ObjCProtocol)))
4014 continue;
4016 // Protocols are in distinct namespaces from everything else.
4017 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
4018 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
4019 D->getIdentifierNamespace() != IDNS)
4020 continue;
4022 // Functions and function templates in the same scope overload
4023 // rather than hide. FIXME: Look for hiding based on function
4024 // signatures!
4025 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4026 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4027 SM == ShadowMaps.rbegin())
4028 continue;
4030 // A shadow declaration that's created by a resolved using declaration
4031 // is not hidden by the same using declaration.
4032 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
4033 cast<UsingShadowDecl>(ND)->getIntroducer() == D)
4034 continue;
4036 // We've found a declaration that hides this one.
4037 return D;
4041 return nullptr;
4044 namespace {
4045 class LookupVisibleHelper {
4046 public:
4047 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
4048 bool LoadExternal)
4049 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
4050 LoadExternal(LoadExternal) {}
4052 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
4053 bool IncludeGlobalScope) {
4054 // Determine the set of using directives available during
4055 // unqualified name lookup.
4056 Scope *Initial = S;
4057 UnqualUsingDirectiveSet UDirs(SemaRef);
4058 if (SemaRef.getLangOpts().CPlusPlus) {
4059 // Find the first namespace or translation-unit scope.
4060 while (S && !isNamespaceOrTranslationUnitScope(S))
4061 S = S->getParent();
4063 UDirs.visitScopeChain(Initial, S);
4065 UDirs.done();
4067 // Look for visible declarations.
4068 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4069 Result.setAllowHidden(Consumer.includeHiddenDecls());
4070 if (!IncludeGlobalScope)
4071 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4072 ShadowContextRAII Shadow(Visited);
4073 lookupInScope(Initial, Result, UDirs);
4076 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
4077 Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
4078 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4079 Result.setAllowHidden(Consumer.includeHiddenDecls());
4080 if (!IncludeGlobalScope)
4081 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4083 ShadowContextRAII Shadow(Visited);
4084 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
4085 /*InBaseClass=*/false);
4088 private:
4089 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
4090 bool QualifiedNameLookup, bool InBaseClass) {
4091 if (!Ctx)
4092 return;
4094 // Make sure we don't visit the same context twice.
4095 if (Visited.visitedContext(Ctx->getPrimaryContext()))
4096 return;
4098 Consumer.EnteredContext(Ctx);
4100 // Outside C++, lookup results for the TU live on identifiers.
4101 if (isa<TranslationUnitDecl>(Ctx) &&
4102 !Result.getSema().getLangOpts().CPlusPlus) {
4103 auto &S = Result.getSema();
4104 auto &Idents = S.Context.Idents;
4106 // Ensure all external identifiers are in the identifier table.
4107 if (LoadExternal)
4108 if (IdentifierInfoLookup *External =
4109 Idents.getExternalIdentifierLookup()) {
4110 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4111 for (StringRef Name = Iter->Next(); !Name.empty();
4112 Name = Iter->Next())
4113 Idents.get(Name);
4116 // Walk all lookup results in the TU for each identifier.
4117 for (const auto &Ident : Idents) {
4118 for (auto I = S.IdResolver.begin(Ident.getValue()),
4119 E = S.IdResolver.end();
4120 I != E; ++I) {
4121 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
4122 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
4123 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4124 Visited.add(ND);
4130 return;
4133 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
4134 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4136 llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;
4137 // We sometimes skip loading namespace-level results (they tend to be huge).
4138 bool Load = LoadExternal ||
4139 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
4140 // Enumerate all of the results in this context.
4141 for (DeclContextLookupResult R :
4142 Load ? Ctx->lookups()
4143 : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
4144 for (auto *D : R) {
4145 if (auto *ND = Result.getAcceptableDecl(D)) {
4146 // Rather than visit immediately, we put ND into a vector and visit
4147 // all decls, in order, outside of this loop. The reason is that
4148 // Consumer.FoundDecl() may invalidate the iterators used in the two
4149 // loops above.
4150 DeclsToVisit.push_back(ND);
4155 for (auto *ND : DeclsToVisit) {
4156 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4157 Visited.add(ND);
4159 DeclsToVisit.clear();
4161 // Traverse using directives for qualified name lookup.
4162 if (QualifiedNameLookup) {
4163 ShadowContextRAII Shadow(Visited);
4164 for (auto *I : Ctx->using_directives()) {
4165 if (!Result.getSema().isVisible(I))
4166 continue;
4167 lookupInDeclContext(I->getNominatedNamespace(), Result,
4168 QualifiedNameLookup, InBaseClass);
4172 // Traverse the contexts of inherited C++ classes.
4173 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
4174 if (!Record->hasDefinition())
4175 return;
4177 for (const auto &B : Record->bases()) {
4178 QualType BaseType = B.getType();
4180 RecordDecl *RD;
4181 if (BaseType->isDependentType()) {
4182 if (!IncludeDependentBases) {
4183 // Don't look into dependent bases, because name lookup can't look
4184 // there anyway.
4185 continue;
4187 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
4188 if (!TST)
4189 continue;
4190 TemplateName TN = TST->getTemplateName();
4191 const auto *TD =
4192 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
4193 if (!TD)
4194 continue;
4195 RD = TD->getTemplatedDecl();
4196 } else {
4197 const auto *Record = BaseType->getAs<RecordType>();
4198 if (!Record)
4199 continue;
4200 RD = Record->getDecl();
4203 // FIXME: It would be nice to be able to determine whether referencing
4204 // a particular member would be ambiguous. For example, given
4206 // struct A { int member; };
4207 // struct B { int member; };
4208 // struct C : A, B { };
4210 // void f(C *c) { c->### }
4212 // accessing 'member' would result in an ambiguity. However, we
4213 // could be smart enough to qualify the member with the base
4214 // class, e.g.,
4216 // c->B::member
4218 // or
4220 // c->A::member
4222 // Find results in this base class (and its bases).
4223 ShadowContextRAII Shadow(Visited);
4224 lookupInDeclContext(RD, Result, QualifiedNameLookup,
4225 /*InBaseClass=*/true);
4229 // Traverse the contexts of Objective-C classes.
4230 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
4231 // Traverse categories.
4232 for (auto *Cat : IFace->visible_categories()) {
4233 ShadowContextRAII Shadow(Visited);
4234 lookupInDeclContext(Cat, Result, QualifiedNameLookup,
4235 /*InBaseClass=*/false);
4238 // Traverse protocols.
4239 for (auto *I : IFace->all_referenced_protocols()) {
4240 ShadowContextRAII Shadow(Visited);
4241 lookupInDeclContext(I, Result, QualifiedNameLookup,
4242 /*InBaseClass=*/false);
4245 // Traverse the superclass.
4246 if (IFace->getSuperClass()) {
4247 ShadowContextRAII Shadow(Visited);
4248 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
4249 /*InBaseClass=*/true);
4252 // If there is an implementation, traverse it. We do this to find
4253 // synthesized ivars.
4254 if (IFace->getImplementation()) {
4255 ShadowContextRAII Shadow(Visited);
4256 lookupInDeclContext(IFace->getImplementation(), Result,
4257 QualifiedNameLookup, InBaseClass);
4259 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
4260 for (auto *I : Protocol->protocols()) {
4261 ShadowContextRAII Shadow(Visited);
4262 lookupInDeclContext(I, Result, QualifiedNameLookup,
4263 /*InBaseClass=*/false);
4265 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
4266 for (auto *I : Category->protocols()) {
4267 ShadowContextRAII Shadow(Visited);
4268 lookupInDeclContext(I, Result, QualifiedNameLookup,
4269 /*InBaseClass=*/false);
4272 // If there is an implementation, traverse it.
4273 if (Category->getImplementation()) {
4274 ShadowContextRAII Shadow(Visited);
4275 lookupInDeclContext(Category->getImplementation(), Result,
4276 QualifiedNameLookup, /*InBaseClass=*/true);
4281 void lookupInScope(Scope *S, LookupResult &Result,
4282 UnqualUsingDirectiveSet &UDirs) {
4283 // No clients run in this mode and it's not supported. Please add tests and
4284 // remove the assertion if you start relying on it.
4285 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4287 if (!S)
4288 return;
4290 if (!S->getEntity() ||
4291 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4292 (S->getEntity())->isFunctionOrMethod()) {
4293 FindLocalExternScope FindLocals(Result);
4294 // Walk through the declarations in this Scope. The consumer might add new
4295 // decls to the scope as part of deserialization, so make a copy first.
4296 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4297 for (Decl *D : ScopeDecls) {
4298 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
4299 if ((ND = Result.getAcceptableDecl(ND))) {
4300 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
4301 Visited.add(ND);
4306 DeclContext *Entity = S->getLookupEntity();
4307 if (Entity) {
4308 // Look into this scope's declaration context, along with any of its
4309 // parent lookup contexts (e.g., enclosing classes), up to the point
4310 // where we hit the context stored in the next outer scope.
4311 DeclContext *OuterCtx = findOuterContext(S);
4313 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
4314 Ctx = Ctx->getLookupParent()) {
4315 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
4316 if (Method->isInstanceMethod()) {
4317 // For instance methods, look for ivars in the method's interface.
4318 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4319 Result.getNameLoc(),
4320 Sema::LookupMemberName);
4321 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4322 lookupInDeclContext(IFace, IvarResult,
4323 /*QualifiedNameLookup=*/false,
4324 /*InBaseClass=*/false);
4328 // We've already performed all of the name lookup that we need
4329 // to for Objective-C methods; the next context will be the
4330 // outer scope.
4331 break;
4334 if (Ctx->isFunctionOrMethod())
4335 continue;
4337 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4338 /*InBaseClass=*/false);
4340 } else if (!S->getParent()) {
4341 // Look into the translation unit scope. We walk through the translation
4342 // unit's declaration context, because the Scope itself won't have all of
4343 // the declarations if we loaded a precompiled header.
4344 // FIXME: We would like the translation unit's Scope object to point to
4345 // the translation unit, so we don't need this special "if" branch.
4346 // However, doing so would force the normal C++ name-lookup code to look
4347 // into the translation unit decl when the IdentifierInfo chains would
4348 // suffice. Once we fix that problem (which is part of a more general
4349 // "don't look in DeclContexts unless we have to" optimization), we can
4350 // eliminate this.
4351 Entity = Result.getSema().Context.getTranslationUnitDecl();
4352 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
4353 /*InBaseClass=*/false);
4356 if (Entity) {
4357 // Lookup visible declarations in any namespaces found by using
4358 // directives.
4359 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4360 lookupInDeclContext(
4361 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4362 /*QualifiedNameLookup=*/false,
4363 /*InBaseClass=*/false);
4366 // Lookup names in the parent scope.
4367 ShadowContextRAII Shadow(Visited);
4368 lookupInScope(S->getParent(), Result, UDirs);
4371 private:
4372 VisibleDeclsRecord Visited;
4373 VisibleDeclConsumer &Consumer;
4374 bool IncludeDependentBases;
4375 bool LoadExternal;
4377 } // namespace
4379 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4380 VisibleDeclConsumer &Consumer,
4381 bool IncludeGlobalScope, bool LoadExternal) {
4382 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4383 LoadExternal);
4384 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4387 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4388 VisibleDeclConsumer &Consumer,
4389 bool IncludeGlobalScope,
4390 bool IncludeDependentBases, bool LoadExternal) {
4391 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4392 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4395 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
4396 /// If GnuLabelLoc is a valid source location, then this is a definition
4397 /// of an __label__ label name, otherwise it is a normal label definition
4398 /// or use.
4399 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
4400 SourceLocation GnuLabelLoc) {
4401 // Do a lookup to see if we have a label with this name already.
4402 NamedDecl *Res = nullptr;
4404 if (GnuLabelLoc.isValid()) {
4405 // Local label definitions always shadow existing labels.
4406 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4407 Scope *S = CurScope;
4408 PushOnScopeChains(Res, S, true);
4409 return cast<LabelDecl>(Res);
4412 // Not a GNU local label.
4413 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
4414 // If we found a label, check to see if it is in the same context as us.
4415 // When in a Block, we don't want to reuse a label in an enclosing function.
4416 if (Res && Res->getDeclContext() != CurContext)
4417 Res = nullptr;
4418 if (!Res) {
4419 // If not forward referenced or defined already, create the backing decl.
4420 Res = LabelDecl::Create(Context, CurContext, Loc, II);
4421 Scope *S = CurScope->getFnParent();
4422 assert(S && "Not in a function?");
4423 PushOnScopeChains(Res, S, true);
4425 return cast<LabelDecl>(Res);
4428 //===----------------------------------------------------------------------===//
4429 // Typo correction
4430 //===----------------------------------------------------------------------===//
4432 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
4433 TypoCorrection &Candidate) {
4434 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4435 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4438 static void LookupPotentialTypoResult(Sema &SemaRef,
4439 LookupResult &Res,
4440 IdentifierInfo *Name,
4441 Scope *S, CXXScopeSpec *SS,
4442 DeclContext *MemberContext,
4443 bool EnteringContext,
4444 bool isObjCIvarLookup,
4445 bool FindHidden);
4447 /// Check whether the declarations found for a typo correction are
4448 /// visible. Set the correction's RequiresImport flag to true if none of the
4449 /// declarations are visible, false otherwise.
4450 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
4451 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4453 for (/**/; DI != DE; ++DI)
4454 if (!LookupResult::isVisible(SemaRef, *DI))
4455 break;
4456 // No filtering needed if all decls are visible.
4457 if (DI == DE) {
4458 TC.setRequiresImport(false);
4459 return;
4462 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4463 bool AnyVisibleDecls = !NewDecls.empty();
4465 for (/**/; DI != DE; ++DI) {
4466 if (LookupResult::isVisible(SemaRef, *DI)) {
4467 if (!AnyVisibleDecls) {
4468 // Found a visible decl, discard all hidden ones.
4469 AnyVisibleDecls = true;
4470 NewDecls.clear();
4472 NewDecls.push_back(*DI);
4473 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4474 NewDecls.push_back(*DI);
4477 if (NewDecls.empty())
4478 TC = TypoCorrection();
4479 else {
4480 TC.setCorrectionDecls(NewDecls);
4481 TC.setRequiresImport(!AnyVisibleDecls);
4485 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
4486 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4487 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4488 static void getNestedNameSpecifierIdentifiers(
4489 NestedNameSpecifier *NNS,
4490 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
4491 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4492 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4493 else
4494 Identifiers.clear();
4496 const IdentifierInfo *II = nullptr;
4498 switch (NNS->getKind()) {
4499 case NestedNameSpecifier::Identifier:
4500 II = NNS->getAsIdentifier();
4501 break;
4503 case NestedNameSpecifier::Namespace:
4504 if (NNS->getAsNamespace()->isAnonymousNamespace())
4505 return;
4506 II = NNS->getAsNamespace()->getIdentifier();
4507 break;
4509 case NestedNameSpecifier::NamespaceAlias:
4510 II = NNS->getAsNamespaceAlias()->getIdentifier();
4511 break;
4513 case NestedNameSpecifier::TypeSpecWithTemplate:
4514 case NestedNameSpecifier::TypeSpec:
4515 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4516 break;
4518 case NestedNameSpecifier::Global:
4519 case NestedNameSpecifier::Super:
4520 return;
4523 if (II)
4524 Identifiers.push_back(II);
4527 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
4528 DeclContext *Ctx, bool InBaseClass) {
4529 // Don't consider hidden names for typo correction.
4530 if (Hiding)
4531 return;
4533 // Only consider entities with identifiers for names, ignoring
4534 // special names (constructors, overloaded operators, selectors,
4535 // etc.).
4536 IdentifierInfo *Name = ND->getIdentifier();
4537 if (!Name)
4538 return;
4540 // Only consider visible declarations and declarations from modules with
4541 // names that exactly match.
4542 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4543 return;
4545 FoundName(Name->getName());
4548 void TypoCorrectionConsumer::FoundName(StringRef Name) {
4549 // Compute the edit distance between the typo and the name of this
4550 // entity, and add the identifier to the list of results.
4551 addName(Name, nullptr);
4554 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
4555 // Compute the edit distance between the typo and this keyword,
4556 // and add the keyword to the list of results.
4557 addName(Keyword, nullptr, nullptr, true);
4560 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4561 NestedNameSpecifier *NNS, bool isKeyword) {
4562 // Use a simple length-based heuristic to determine the minimum possible
4563 // edit distance. If the minimum isn't good enough, bail out early.
4564 StringRef TypoStr = Typo->getName();
4565 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4566 if (MinED && TypoStr.size() / MinED < 3)
4567 return;
4569 // Compute an upper bound on the allowable edit distance, so that the
4570 // edit-distance algorithm can short-circuit.
4571 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4572 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4573 if (ED > UpperBound) return;
4575 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4576 if (isKeyword) TC.makeKeyword();
4577 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4578 addCorrection(TC);
4581 static const unsigned MaxTypoDistanceResultSets = 5;
4583 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
4584 StringRef TypoStr = Typo->getName();
4585 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4587 // For very short typos, ignore potential corrections that have a different
4588 // base identifier from the typo or which have a normalized edit distance
4589 // longer than the typo itself.
4590 if (TypoStr.size() < 3 &&
4591 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4592 return;
4594 // If the correction is resolved but is not viable, ignore it.
4595 if (Correction.isResolved()) {
4596 checkCorrectionVisibility(SemaRef, Correction);
4597 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4598 return;
4601 TypoResultList &CList =
4602 CorrectionResults[Correction.getEditDistance(false)][Name];
4604 if (!CList.empty() && !CList.back().isResolved())
4605 CList.pop_back();
4606 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4607 auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
4608 return TypoCorr.getCorrectionDecl() == NewND;
4610 if (RI != CList.end()) {
4611 // The Correction refers to a decl already in the list. No insertion is
4612 // necessary and all further cases will return.
4614 auto IsDeprecated = [](Decl *D) {
4615 while (D) {
4616 if (D->isDeprecated())
4617 return true;
4618 D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
4620 return false;
4623 // Prefer non deprecated Corrections over deprecated and only then
4624 // sort using an alphabetical order.
4625 std::pair<bool, std::string> NewKey = {
4626 IsDeprecated(Correction.getFoundDecl()),
4627 Correction.getAsString(SemaRef.getLangOpts())};
4629 std::pair<bool, std::string> PrevKey = {
4630 IsDeprecated(RI->getFoundDecl()),
4631 RI->getAsString(SemaRef.getLangOpts())};
4633 if (NewKey < PrevKey)
4634 *RI = Correction;
4635 return;
4638 if (CList.empty() || Correction.isResolved())
4639 CList.push_back(Correction);
4641 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4642 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4645 void TypoCorrectionConsumer::addNamespaces(
4646 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4647 SearchNamespaces = true;
4649 for (auto KNPair : KnownNamespaces)
4650 Namespaces.addNameSpecifier(KNPair.first);
4652 bool SSIsTemplate = false;
4653 if (NestedNameSpecifier *NNS =
4654 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4655 if (const Type *T = NNS->getAsType())
4656 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4658 // Do not transform this into an iterator-based loop. The loop body can
4659 // trigger the creation of further types (through lazy deserialization) and
4660 // invalid iterators into this list.
4661 auto &Types = SemaRef.getASTContext().getTypes();
4662 for (unsigned I = 0; I != Types.size(); ++I) {
4663 const auto *TI = Types[I];
4664 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4665 CD = CD->getCanonicalDecl();
4666 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4667 !CD->isUnion() && CD->getIdentifier() &&
4668 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4669 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4670 Namespaces.addNameSpecifier(CD);
4675 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4676 if (++CurrentTCIndex < ValidatedCorrections.size())
4677 return ValidatedCorrections[CurrentTCIndex];
4679 CurrentTCIndex = ValidatedCorrections.size();
4680 while (!CorrectionResults.empty()) {
4681 auto DI = CorrectionResults.begin();
4682 if (DI->second.empty()) {
4683 CorrectionResults.erase(DI);
4684 continue;
4687 auto RI = DI->second.begin();
4688 if (RI->second.empty()) {
4689 DI->second.erase(RI);
4690 performQualifiedLookups();
4691 continue;
4694 TypoCorrection TC = RI->second.pop_back_val();
4695 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4696 ValidatedCorrections.push_back(TC);
4697 return ValidatedCorrections[CurrentTCIndex];
4700 return ValidatedCorrections[0]; // The empty correction.
4703 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4704 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4705 DeclContext *TempMemberContext = MemberContext;
4706 CXXScopeSpec *TempSS = SS.get();
4707 retry_lookup:
4708 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4709 EnteringContext,
4710 CorrectionValidator->IsObjCIvarLookup,
4711 Name == Typo && !Candidate.WillReplaceSpecifier());
4712 switch (Result.getResultKind()) {
4713 case LookupResult::NotFound:
4714 case LookupResult::NotFoundInCurrentInstantiation:
4715 case LookupResult::FoundUnresolvedValue:
4716 if (TempSS) {
4717 // Immediately retry the lookup without the given CXXScopeSpec
4718 TempSS = nullptr;
4719 Candidate.WillReplaceSpecifier(true);
4720 goto retry_lookup;
4722 if (TempMemberContext) {
4723 if (SS && !TempSS)
4724 TempSS = SS.get();
4725 TempMemberContext = nullptr;
4726 goto retry_lookup;
4728 if (SearchNamespaces)
4729 QualifiedResults.push_back(Candidate);
4730 break;
4732 case LookupResult::Ambiguous:
4733 // We don't deal with ambiguities.
4734 break;
4736 case LookupResult::Found:
4737 case LookupResult::FoundOverloaded:
4738 // Store all of the Decls for overloaded symbols
4739 for (auto *TRD : Result)
4740 Candidate.addCorrectionDecl(TRD);
4741 checkCorrectionVisibility(SemaRef, Candidate);
4742 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4743 if (SearchNamespaces)
4744 QualifiedResults.push_back(Candidate);
4745 break;
4747 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4748 return true;
4750 return false;
4753 void TypoCorrectionConsumer::performQualifiedLookups() {
4754 unsigned TypoLen = Typo->getName().size();
4755 for (const TypoCorrection &QR : QualifiedResults) {
4756 for (const auto &NSI : Namespaces) {
4757 DeclContext *Ctx = NSI.DeclCtx;
4758 const Type *NSType = NSI.NameSpecifier->getAsType();
4760 // If the current NestedNameSpecifier refers to a class and the
4761 // current correction candidate is the name of that class, then skip
4762 // it as it is unlikely a qualified version of the class' constructor
4763 // is an appropriate correction.
4764 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4765 nullptr) {
4766 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4767 continue;
4770 TypoCorrection TC(QR);
4771 TC.ClearCorrectionDecls();
4772 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4773 TC.setQualifierDistance(NSI.EditDistance);
4774 TC.setCallbackDistance(0); // Reset the callback distance
4776 // If the current correction candidate and namespace combination are
4777 // too far away from the original typo based on the normalized edit
4778 // distance, then skip performing a qualified name lookup.
4779 unsigned TmpED = TC.getEditDistance(true);
4780 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4781 TypoLen / TmpED < 3)
4782 continue;
4784 Result.clear();
4785 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4786 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4787 continue;
4789 // Any corrections added below will be validated in subsequent
4790 // iterations of the main while() loop over the Consumer's contents.
4791 switch (Result.getResultKind()) {
4792 case LookupResult::Found:
4793 case LookupResult::FoundOverloaded: {
4794 if (SS && SS->isValid()) {
4795 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4796 std::string OldQualified;
4797 llvm::raw_string_ostream OldOStream(OldQualified);
4798 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4799 OldOStream << Typo->getName();
4800 // If correction candidate would be an identical written qualified
4801 // identifier, then the existing CXXScopeSpec probably included a
4802 // typedef that didn't get accounted for properly.
4803 if (OldOStream.str() == NewQualified)
4804 break;
4806 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4807 TRD != TRDEnd; ++TRD) {
4808 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4809 NSType ? NSType->getAsCXXRecordDecl()
4810 : nullptr,
4811 TRD.getPair()) == Sema::AR_accessible)
4812 TC.addCorrectionDecl(*TRD);
4814 if (TC.isResolved()) {
4815 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4816 addCorrection(TC);
4818 break;
4820 case LookupResult::NotFound:
4821 case LookupResult::NotFoundInCurrentInstantiation:
4822 case LookupResult::Ambiguous:
4823 case LookupResult::FoundUnresolvedValue:
4824 break;
4828 QualifiedResults.clear();
4831 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4832 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4833 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4834 if (NestedNameSpecifier *NNS =
4835 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4836 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4837 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4839 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4841 // Build the list of identifiers that would be used for an absolute
4842 // (from the global context) NestedNameSpecifier referring to the current
4843 // context.
4844 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4845 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4846 CurContextIdentifiers.push_back(ND->getIdentifier());
4849 // Add the global context as a NestedNameSpecifier
4850 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4851 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4852 DistanceMap[1].push_back(SI);
4855 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4856 DeclContext *Start) -> DeclContextList {
4857 assert(Start && "Building a context chain from a null context");
4858 DeclContextList Chain;
4859 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4860 DC = DC->getLookupParent()) {
4861 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4862 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4863 !(ND && ND->isAnonymousNamespace()))
4864 Chain.push_back(DC->getPrimaryContext());
4866 return Chain;
4869 unsigned
4870 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4871 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4872 unsigned NumSpecifiers = 0;
4873 for (DeclContext *C : llvm::reverse(DeclChain)) {
4874 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4875 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4876 ++NumSpecifiers;
4877 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4878 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4879 RD->getTypeForDecl());
4880 ++NumSpecifiers;
4883 return NumSpecifiers;
4886 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4887 DeclContext *Ctx) {
4888 NestedNameSpecifier *NNS = nullptr;
4889 unsigned NumSpecifiers = 0;
4890 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4891 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4893 // Eliminate common elements from the two DeclContext chains.
4894 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4895 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4896 break;
4897 NamespaceDeclChain.pop_back();
4900 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4901 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4903 // Add an explicit leading '::' specifier if needed.
4904 if (NamespaceDeclChain.empty()) {
4905 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4906 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4907 NumSpecifiers =
4908 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4909 } else if (NamedDecl *ND =
4910 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4911 IdentifierInfo *Name = ND->getIdentifier();
4912 bool SameNameSpecifier = false;
4913 if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
4914 std::string NewNameSpecifier;
4915 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4916 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4917 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4918 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4919 SpecifierOStream.flush();
4920 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4922 if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
4923 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4924 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4925 NumSpecifiers =
4926 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4930 // If the built NestedNameSpecifier would be replacing an existing
4931 // NestedNameSpecifier, use the number of component identifiers that
4932 // would need to be changed as the edit distance instead of the number
4933 // of components in the built NestedNameSpecifier.
4934 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4935 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4936 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4937 NumSpecifiers = llvm::ComputeEditDistance(
4938 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4939 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
4942 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4943 DistanceMap[NumSpecifiers].push_back(SI);
4946 /// Perform name lookup for a possible result for typo correction.
4947 static void LookupPotentialTypoResult(Sema &SemaRef,
4948 LookupResult &Res,
4949 IdentifierInfo *Name,
4950 Scope *S, CXXScopeSpec *SS,
4951 DeclContext *MemberContext,
4952 bool EnteringContext,
4953 bool isObjCIvarLookup,
4954 bool FindHidden) {
4955 Res.suppressDiagnostics();
4956 Res.clear();
4957 Res.setLookupName(Name);
4958 Res.setAllowHidden(FindHidden);
4959 if (MemberContext) {
4960 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4961 if (isObjCIvarLookup) {
4962 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4963 Res.addDecl(Ivar);
4964 Res.resolveKind();
4965 return;
4969 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4970 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
4971 Res.addDecl(Prop);
4972 Res.resolveKind();
4973 return;
4977 SemaRef.LookupQualifiedName(Res, MemberContext);
4978 return;
4981 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
4982 EnteringContext);
4984 // Fake ivar lookup; this should really be part of
4985 // LookupParsedName.
4986 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4987 if (Method->isInstanceMethod() && Method->getClassInterface() &&
4988 (Res.empty() ||
4989 (Res.isSingleResult() &&
4990 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
4991 if (ObjCIvarDecl *IV
4992 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4993 Res.addDecl(IV);
4994 Res.resolveKind();
5000 /// Add keywords to the consumer as possible typo corrections.
5001 static void AddKeywordsToConsumer(Sema &SemaRef,
5002 TypoCorrectionConsumer &Consumer,
5003 Scope *S, CorrectionCandidateCallback &CCC,
5004 bool AfterNestedNameSpecifier) {
5005 if (AfterNestedNameSpecifier) {
5006 // For 'X::', we know exactly which keywords can appear next.
5007 Consumer.addKeywordResult("template");
5008 if (CCC.WantExpressionKeywords)
5009 Consumer.addKeywordResult("operator");
5010 return;
5013 if (CCC.WantObjCSuper)
5014 Consumer.addKeywordResult("super");
5016 if (CCC.WantTypeSpecifiers) {
5017 // Add type-specifier keywords to the set of results.
5018 static const char *const CTypeSpecs[] = {
5019 "char", "const", "double", "enum", "float", "int", "long", "short",
5020 "signed", "struct", "union", "unsigned", "void", "volatile",
5021 "_Complex", "_Imaginary",
5022 // storage-specifiers as well
5023 "extern", "inline", "static", "typedef"
5026 for (const auto *CTS : CTypeSpecs)
5027 Consumer.addKeywordResult(CTS);
5029 if (SemaRef.getLangOpts().C99)
5030 Consumer.addKeywordResult("restrict");
5031 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
5032 Consumer.addKeywordResult("bool");
5033 else if (SemaRef.getLangOpts().C99)
5034 Consumer.addKeywordResult("_Bool");
5036 if (SemaRef.getLangOpts().CPlusPlus) {
5037 Consumer.addKeywordResult("class");
5038 Consumer.addKeywordResult("typename");
5039 Consumer.addKeywordResult("wchar_t");
5041 if (SemaRef.getLangOpts().CPlusPlus11) {
5042 Consumer.addKeywordResult("char16_t");
5043 Consumer.addKeywordResult("char32_t");
5044 Consumer.addKeywordResult("constexpr");
5045 Consumer.addKeywordResult("decltype");
5046 Consumer.addKeywordResult("thread_local");
5050 if (SemaRef.getLangOpts().GNUKeywords)
5051 Consumer.addKeywordResult("typeof");
5052 } else if (CCC.WantFunctionLikeCasts) {
5053 static const char *const CastableTypeSpecs[] = {
5054 "char", "double", "float", "int", "long", "short",
5055 "signed", "unsigned", "void"
5057 for (auto *kw : CastableTypeSpecs)
5058 Consumer.addKeywordResult(kw);
5061 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
5062 Consumer.addKeywordResult("const_cast");
5063 Consumer.addKeywordResult("dynamic_cast");
5064 Consumer.addKeywordResult("reinterpret_cast");
5065 Consumer.addKeywordResult("static_cast");
5068 if (CCC.WantExpressionKeywords) {
5069 Consumer.addKeywordResult("sizeof");
5070 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
5071 Consumer.addKeywordResult("false");
5072 Consumer.addKeywordResult("true");
5075 if (SemaRef.getLangOpts().CPlusPlus) {
5076 static const char *const CXXExprs[] = {
5077 "delete", "new", "operator", "throw", "typeid"
5079 for (const auto *CE : CXXExprs)
5080 Consumer.addKeywordResult(CE);
5082 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
5083 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
5084 Consumer.addKeywordResult("this");
5086 if (SemaRef.getLangOpts().CPlusPlus11) {
5087 Consumer.addKeywordResult("alignof");
5088 Consumer.addKeywordResult("nullptr");
5092 if (SemaRef.getLangOpts().C11) {
5093 // FIXME: We should not suggest _Alignof if the alignof macro
5094 // is present.
5095 Consumer.addKeywordResult("_Alignof");
5099 if (CCC.WantRemainingKeywords) {
5100 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
5101 // Statements.
5102 static const char *const CStmts[] = {
5103 "do", "else", "for", "goto", "if", "return", "switch", "while" };
5104 for (const auto *CS : CStmts)
5105 Consumer.addKeywordResult(CS);
5107 if (SemaRef.getLangOpts().CPlusPlus) {
5108 Consumer.addKeywordResult("catch");
5109 Consumer.addKeywordResult("try");
5112 if (S && S->getBreakParent())
5113 Consumer.addKeywordResult("break");
5115 if (S && S->getContinueParent())
5116 Consumer.addKeywordResult("continue");
5118 if (SemaRef.getCurFunction() &&
5119 !SemaRef.getCurFunction()->SwitchStack.empty()) {
5120 Consumer.addKeywordResult("case");
5121 Consumer.addKeywordResult("default");
5123 } else {
5124 if (SemaRef.getLangOpts().CPlusPlus) {
5125 Consumer.addKeywordResult("namespace");
5126 Consumer.addKeywordResult("template");
5129 if (S && S->isClassScope()) {
5130 Consumer.addKeywordResult("explicit");
5131 Consumer.addKeywordResult("friend");
5132 Consumer.addKeywordResult("mutable");
5133 Consumer.addKeywordResult("private");
5134 Consumer.addKeywordResult("protected");
5135 Consumer.addKeywordResult("public");
5136 Consumer.addKeywordResult("virtual");
5140 if (SemaRef.getLangOpts().CPlusPlus) {
5141 Consumer.addKeywordResult("using");
5143 if (SemaRef.getLangOpts().CPlusPlus11)
5144 Consumer.addKeywordResult("static_assert");
5149 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5150 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5151 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5152 DeclContext *MemberContext, bool EnteringContext,
5153 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
5155 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
5156 DisableTypoCorrection)
5157 return nullptr;
5159 // In Microsoft mode, don't perform typo correction in a template member
5160 // function dependent context because it interferes with the "lookup into
5161 // dependent bases of class templates" feature.
5162 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
5163 isa<CXXMethodDecl>(CurContext))
5164 return nullptr;
5166 // We only attempt to correct typos for identifiers.
5167 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5168 if (!Typo)
5169 return nullptr;
5171 // If the scope specifier itself was invalid, don't try to correct
5172 // typos.
5173 if (SS && SS->isInvalid())
5174 return nullptr;
5176 // Never try to correct typos during any kind of code synthesis.
5177 if (!CodeSynthesisContexts.empty())
5178 return nullptr;
5180 // Don't try to correct 'super'.
5181 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
5182 return nullptr;
5184 // Abort if typo correction already failed for this specific typo.
5185 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
5186 if (locs != TypoCorrectionFailures.end() &&
5187 locs->second.count(TypoName.getLoc()))
5188 return nullptr;
5190 // Don't try to correct the identifier "vector" when in AltiVec mode.
5191 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5192 // remove this workaround.
5193 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
5194 return nullptr;
5196 // Provide a stop gap for files that are just seriously broken. Trying
5197 // to correct all typos can turn into a HUGE performance penalty, causing
5198 // some files to take minutes to get rejected by the parser.
5199 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
5200 if (Limit && TyposCorrected >= Limit)
5201 return nullptr;
5202 ++TyposCorrected;
5204 // If we're handling a missing symbol error, using modules, and the
5205 // special search all modules option is used, look for a missing import.
5206 if (ErrorRecovery && getLangOpts().Modules &&
5207 getLangOpts().ModulesSearchAll) {
5208 // The following has the side effect of loading the missing module.
5209 getModuleLoader().lookupMissingImports(Typo->getName(),
5210 TypoName.getBeginLoc());
5213 // Extend the lifetime of the callback. We delayed this until here
5214 // to avoid allocations in the hot path (which is where no typo correction
5215 // occurs). Note that CorrectionCandidateCallback is polymorphic and
5216 // initially stack-allocated.
5217 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
5218 auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5219 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
5220 EnteringContext);
5222 // Perform name lookup to find visible, similarly-named entities.
5223 bool IsUnqualifiedLookup = false;
5224 DeclContext *QualifiedDC = MemberContext;
5225 if (MemberContext) {
5226 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
5228 // Look in qualified interfaces.
5229 if (OPT) {
5230 for (auto *I : OPT->quals())
5231 LookupVisibleDecls(I, LookupKind, *Consumer);
5233 } else if (SS && SS->isSet()) {
5234 QualifiedDC = computeDeclContext(*SS, EnteringContext);
5235 if (!QualifiedDC)
5236 return nullptr;
5238 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
5239 } else {
5240 IsUnqualifiedLookup = true;
5243 // Determine whether we are going to search in the various namespaces for
5244 // corrections.
5245 bool SearchNamespaces
5246 = getLangOpts().CPlusPlus &&
5247 (IsUnqualifiedLookup || (SS && SS->isSet()));
5249 if (IsUnqualifiedLookup || SearchNamespaces) {
5250 // For unqualified lookup, look through all of the names that we have
5251 // seen in this translation unit.
5252 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5253 for (const auto &I : Context.Idents)
5254 Consumer->FoundName(I.getKey());
5256 // Walk through identifiers in external identifier sources.
5257 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5258 if (IdentifierInfoLookup *External
5259 = Context.Idents.getExternalIdentifierLookup()) {
5260 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5261 do {
5262 StringRef Name = Iter->Next();
5263 if (Name.empty())
5264 break;
5266 Consumer->FoundName(Name);
5267 } while (true);
5271 AddKeywordsToConsumer(*this, *Consumer, S,
5272 *Consumer->getCorrectionValidator(),
5273 SS && SS->isNotEmpty());
5275 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5276 // to search those namespaces.
5277 if (SearchNamespaces) {
5278 // Load any externally-known namespaces.
5279 if (ExternalSource && !LoadedExternalKnownNamespaces) {
5280 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
5281 LoadedExternalKnownNamespaces = true;
5282 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
5283 for (auto *N : ExternalKnownNamespaces)
5284 KnownNamespaces[N] = true;
5287 Consumer->addNamespaces(KnownNamespaces);
5290 return Consumer;
5293 /// Try to "correct" a typo in the source code by finding
5294 /// visible declarations whose names are similar to the name that was
5295 /// present in the source code.
5297 /// \param TypoName the \c DeclarationNameInfo structure that contains
5298 /// the name that was present in the source code along with its location.
5300 /// \param LookupKind the name-lookup criteria used to search for the name.
5302 /// \param S the scope in which name lookup occurs.
5304 /// \param SS the nested-name-specifier that precedes the name we're
5305 /// looking for, if present.
5307 /// \param CCC A CorrectionCandidateCallback object that provides further
5308 /// validation of typo correction candidates. It also provides flags for
5309 /// determining the set of keywords permitted.
5311 /// \param MemberContext if non-NULL, the context in which to look for
5312 /// a member access expression.
5314 /// \param EnteringContext whether we're entering the context described by
5315 /// the nested-name-specifier SS.
5317 /// \param OPT when non-NULL, the search for visible declarations will
5318 /// also walk the protocols in the qualified interfaces of \p OPT.
5320 /// \returns a \c TypoCorrection containing the corrected name if the typo
5321 /// along with information such as the \c NamedDecl where the corrected name
5322 /// was declared, and any additional \c NestedNameSpecifier needed to access
5323 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
5324 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
5325 Sema::LookupNameKind LookupKind,
5326 Scope *S, CXXScopeSpec *SS,
5327 CorrectionCandidateCallback &CCC,
5328 CorrectTypoKind Mode,
5329 DeclContext *MemberContext,
5330 bool EnteringContext,
5331 const ObjCObjectPointerType *OPT,
5332 bool RecordFailure) {
5333 // Always let the ExternalSource have the first chance at correction, even
5334 // if we would otherwise have given up.
5335 if (ExternalSource) {
5336 if (TypoCorrection Correction =
5337 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
5338 MemberContext, EnteringContext, OPT))
5339 return Correction;
5342 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5343 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5344 // some instances of CTC_Unknown, while WantRemainingKeywords is true
5345 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5346 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
5348 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5349 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5350 MemberContext, EnteringContext,
5351 OPT, Mode == CTK_ErrorRecovery);
5353 if (!Consumer)
5354 return TypoCorrection();
5356 // If we haven't found anything, we're done.
5357 if (Consumer->empty())
5358 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5360 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5361 // is not more that about a third of the length of the typo's identifier.
5362 unsigned ED = Consumer->getBestEditDistance(true);
5363 unsigned TypoLen = Typo->getName().size();
5364 if (ED > 0 && TypoLen / ED < 3)
5365 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5367 TypoCorrection BestTC = Consumer->getNextCorrection();
5368 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5369 if (!BestTC)
5370 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5372 ED = BestTC.getEditDistance();
5374 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5375 // If this was an unqualified lookup and we believe the callback
5376 // object wouldn't have filtered out possible corrections, note
5377 // that no correction was found.
5378 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5381 // If only a single name remains, return that result.
5382 if (!SecondBestTC ||
5383 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
5384 const TypoCorrection &Result = BestTC;
5386 // Don't correct to a keyword that's the same as the typo; the keyword
5387 // wasn't actually in scope.
5388 if (ED == 0 && Result.isKeyword())
5389 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5391 TypoCorrection TC = Result;
5392 TC.setCorrectionRange(SS, TypoName);
5393 checkCorrectionVisibility(*this, TC);
5394 return TC;
5395 } else if (SecondBestTC && ObjCMessageReceiver) {
5396 // Prefer 'super' when we're completing in a message-receiver
5397 // context.
5399 if (BestTC.getCorrection().getAsString() != "super") {
5400 if (SecondBestTC.getCorrection().getAsString() == "super")
5401 BestTC = SecondBestTC;
5402 else if ((*Consumer)["super"].front().isKeyword())
5403 BestTC = (*Consumer)["super"].front();
5405 // Don't correct to a keyword that's the same as the typo; the keyword
5406 // wasn't actually in scope.
5407 if (BestTC.getEditDistance() == 0 ||
5408 BestTC.getCorrection().getAsString() != "super")
5409 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5411 BestTC.setCorrectionRange(SS, TypoName);
5412 return BestTC;
5415 // Record the failure's location if needed and return an empty correction. If
5416 // this was an unqualified lookup and we believe the callback object did not
5417 // filter out possible corrections, also cache the failure for the typo.
5418 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
5421 /// Try to "correct" a typo in the source code by finding
5422 /// visible declarations whose names are similar to the name that was
5423 /// present in the source code.
5425 /// \param TypoName the \c DeclarationNameInfo structure that contains
5426 /// the name that was present in the source code along with its location.
5428 /// \param LookupKind the name-lookup criteria used to search for the name.
5430 /// \param S the scope in which name lookup occurs.
5432 /// \param SS the nested-name-specifier that precedes the name we're
5433 /// looking for, if present.
5435 /// \param CCC A CorrectionCandidateCallback object that provides further
5436 /// validation of typo correction candidates. It also provides flags for
5437 /// determining the set of keywords permitted.
5439 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
5440 /// diagnostics when the actual typo correction is attempted.
5442 /// \param TRC A TypoRecoveryCallback functor that will be used to build an
5443 /// Expr from a typo correction candidate.
5445 /// \param MemberContext if non-NULL, the context in which to look for
5446 /// a member access expression.
5448 /// \param EnteringContext whether we're entering the context described by
5449 /// the nested-name-specifier SS.
5451 /// \param OPT when non-NULL, the search for visible declarations will
5452 /// also walk the protocols in the qualified interfaces of \p OPT.
5454 /// \returns a new \c TypoExpr that will later be replaced in the AST with an
5455 /// Expr representing the result of performing typo correction, or nullptr if
5456 /// typo correction is not possible. If nullptr is returned, no diagnostics will
5457 /// be emitted and it is the responsibility of the caller to emit any that are
5458 /// needed.
5459 TypoExpr *Sema::CorrectTypoDelayed(
5460 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5461 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5462 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
5463 DeclContext *MemberContext, bool EnteringContext,
5464 const ObjCObjectPointerType *OPT) {
5465 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5466 MemberContext, EnteringContext,
5467 OPT, Mode == CTK_ErrorRecovery);
5469 // Give the external sema source a chance to correct the typo.
5470 TypoCorrection ExternalTypo;
5471 if (ExternalSource && Consumer) {
5472 ExternalTypo = ExternalSource->CorrectTypo(
5473 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
5474 MemberContext, EnteringContext, OPT);
5475 if (ExternalTypo)
5476 Consumer->addCorrection(ExternalTypo);
5479 if (!Consumer || Consumer->empty())
5480 return nullptr;
5482 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5483 // is not more that about a third of the length of the typo's identifier.
5484 unsigned ED = Consumer->getBestEditDistance(true);
5485 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5486 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
5487 return nullptr;
5488 ExprEvalContexts.back().NumTypos++;
5489 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),
5490 TypoName.getLoc());
5493 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
5494 if (!CDecl) return;
5496 if (isKeyword())
5497 CorrectionDecls.clear();
5499 CorrectionDecls.push_back(CDecl);
5501 if (!CorrectionName)
5502 CorrectionName = CDecl->getDeclName();
5505 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5506 if (CorrectionNameSpec) {
5507 std::string tmpBuffer;
5508 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5509 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
5510 PrefixOStream << CorrectionName;
5511 return PrefixOStream.str();
5514 return CorrectionName.getAsString();
5517 bool CorrectionCandidateCallback::ValidateCandidate(
5518 const TypoCorrection &candidate) {
5519 if (!candidate.isResolved())
5520 return true;
5522 if (candidate.isKeyword())
5523 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
5524 WantRemainingKeywords || WantObjCSuper;
5526 bool HasNonType = false;
5527 bool HasStaticMethod = false;
5528 bool HasNonStaticMethod = false;
5529 for (Decl *D : candidate) {
5530 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5531 D = FTD->getTemplatedDecl();
5532 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5533 if (Method->isStatic())
5534 HasStaticMethod = true;
5535 else
5536 HasNonStaticMethod = true;
5538 if (!isa<TypeDecl>(D))
5539 HasNonType = true;
5542 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5543 !candidate.getCorrectionSpecifier())
5544 return false;
5546 return WantTypeSpecifiers || HasNonType;
5549 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
5550 bool HasExplicitTemplateArgs,
5551 MemberExpr *ME)
5552 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5553 CurContext(SemaRef.CurContext), MemberFn(ME) {
5554 WantTypeSpecifiers = false;
5555 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5556 !HasExplicitTemplateArgs && NumArgs == 1;
5557 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5558 WantRemainingKeywords = false;
5561 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
5562 if (!candidate.getCorrectionDecl())
5563 return candidate.isKeyword();
5565 for (auto *C : candidate) {
5566 FunctionDecl *FD = nullptr;
5567 NamedDecl *ND = C->getUnderlyingDecl();
5568 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5569 FD = FTD->getTemplatedDecl();
5570 if (!HasExplicitTemplateArgs && !FD) {
5571 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5572 // If the Decl is neither a function nor a template function,
5573 // determine if it is a pointer or reference to a function. If so,
5574 // check against the number of arguments expected for the pointee.
5575 QualType ValType = cast<ValueDecl>(ND)->getType();
5576 if (ValType.isNull())
5577 continue;
5578 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5579 ValType = ValType->getPointeeType();
5580 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5581 if (FPT->getNumParams() == NumArgs)
5582 return true;
5586 // A typo for a function-style cast can look like a function call in C++.
5587 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5588 : isa<TypeDecl>(ND)) &&
5589 CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5590 // Only a class or class template can take two or more arguments.
5591 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5593 // Skip the current candidate if it is not a FunctionDecl or does not accept
5594 // the current number of arguments.
5595 if (!FD || !(FD->getNumParams() >= NumArgs &&
5596 FD->getMinRequiredArguments() <= NumArgs))
5597 continue;
5599 // If the current candidate is a non-static C++ method, skip the candidate
5600 // unless the method being corrected--or the current DeclContext, if the
5601 // function being corrected is not a method--is a method in the same class
5602 // or a descendent class of the candidate's parent class.
5603 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5604 if (MemberFn || !MD->isStatic()) {
5605 CXXMethodDecl *CurMD =
5606 MemberFn
5607 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
5608 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
5609 CXXRecordDecl *CurRD =
5610 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5611 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5612 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5613 continue;
5616 return true;
5618 return false;
5621 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5622 const PartialDiagnostic &TypoDiag,
5623 bool ErrorRecovery) {
5624 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5625 ErrorRecovery);
5628 /// Find which declaration we should import to provide the definition of
5629 /// the given declaration.
5630 static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5631 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5632 return VD->getDefinition();
5633 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5634 return FD->getDefinition();
5635 if (TagDecl *TD = dyn_cast<TagDecl>(D))
5636 return TD->getDefinition();
5637 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
5638 return ID->getDefinition();
5639 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
5640 return PD->getDefinition();
5641 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
5642 if (NamedDecl *TTD = TD->getTemplatedDecl())
5643 return getDefinitionToImport(TTD);
5644 return nullptr;
5647 void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
5648 MissingImportKind MIK, bool Recover) {
5649 // Suggest importing a module providing the definition of this entity, if
5650 // possible.
5651 NamedDecl *Def = getDefinitionToImport(Decl);
5652 if (!Def)
5653 Def = Decl;
5655 Module *Owner = getOwningModule(Def);
5656 assert(Owner && "definition of hidden declaration is not in a module");
5658 llvm::SmallVector<Module*, 8> OwningModules;
5659 OwningModules.push_back(Owner);
5660 auto Merged = Context.getModulesWithMergedDefinition(Def);
5661 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5663 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5664 Recover);
5667 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5668 /// suggesting the addition of a #include of the specified file.
5669 static std::string getHeaderNameForHeader(Preprocessor &PP, const FileEntry *E,
5670 llvm::StringRef IncludingFile) {
5671 bool IsSystem = false;
5672 auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5673 E, IncludingFile, &IsSystem);
5674 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5677 void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5678 SourceLocation DeclLoc,
5679 ArrayRef<Module *> Modules,
5680 MissingImportKind MIK, bool Recover) {
5681 assert(!Modules.empty());
5683 auto NotePrevious = [&] {
5684 // FIXME: Suppress the note backtrace even under
5685 // -fdiagnostics-show-note-include-stack. We don't care how this
5686 // declaration was previously reached.
5687 Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
5690 // Weed out duplicates from module list.
5691 llvm::SmallVector<Module*, 8> UniqueModules;
5692 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5693 for (auto *M : Modules) {
5694 if (M->isGlobalModule() || M->isPrivateModule())
5695 continue;
5696 if (UniqueModuleSet.insert(M).second)
5697 UniqueModules.push_back(M);
5700 // Try to find a suitable header-name to #include.
5701 std::string HeaderName;
5702 if (const FileEntry *Header =
5703 PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5704 if (const FileEntry *FE =
5705 SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5706 HeaderName = getHeaderNameForHeader(PP, Header, FE->tryGetRealPathName());
5709 // If we have a #include we should suggest, or if all definition locations
5710 // were in global module fragments, don't suggest an import.
5711 if (!HeaderName.empty() || UniqueModules.empty()) {
5712 // FIXME: Find a smart place to suggest inserting a #include, and add
5713 // a FixItHint there.
5714 Diag(UseLoc, diag::err_module_unimported_use_header)
5715 << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5716 // Produce a note showing where the entity was declared.
5717 NotePrevious();
5718 if (Recover)
5719 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5720 return;
5723 Modules = UniqueModules;
5725 if (Modules.size() > 1) {
5726 std::string ModuleList;
5727 unsigned N = 0;
5728 for (Module *M : Modules) {
5729 ModuleList += "\n ";
5730 if (++N == 5 && N != Modules.size()) {
5731 ModuleList += "[...]";
5732 break;
5734 ModuleList += M->getFullModuleName();
5737 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5738 << (int)MIK << Decl << ModuleList;
5739 } else {
5740 // FIXME: Add a FixItHint that imports the corresponding module.
5741 Diag(UseLoc, diag::err_module_unimported_use)
5742 << (int)MIK << Decl << Modules[0]->getFullModuleName();
5745 NotePrevious();
5747 // Try to recover by implicitly importing this module.
5748 if (Recover)
5749 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5752 /// Diagnose a successfully-corrected typo. Separated from the correction
5753 /// itself to allow external validation of the result, etc.
5755 /// \param Correction The result of performing typo correction.
5756 /// \param TypoDiag The diagnostic to produce. This will have the corrected
5757 /// string added to it (and usually also a fixit).
5758 /// \param PrevNote A note to use when indicating the location of the entity to
5759 /// which we are correcting. Will have the correction string added to it.
5760 /// \param ErrorRecovery If \c true (the default), the caller is going to
5761 /// recover from the typo as if the corrected string had been typed.
5762 /// In this case, \c PDiag must be an error, and we will attach a fixit
5763 /// to it.
5764 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5765 const PartialDiagnostic &TypoDiag,
5766 const PartialDiagnostic &PrevNote,
5767 bool ErrorRecovery) {
5768 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5769 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5770 FixItHint FixTypo = FixItHint::CreateReplacement(
5771 Correction.getCorrectionRange(), CorrectedStr);
5773 // Maybe we're just missing a module import.
5774 if (Correction.requiresImport()) {
5775 NamedDecl *Decl = Correction.getFoundDecl();
5776 assert(Decl && "import required but no declaration to import");
5778 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
5779 MissingImportKind::Declaration, ErrorRecovery);
5780 return;
5783 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5784 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5786 NamedDecl *ChosenDecl =
5787 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5788 if (PrevNote.getDiagID() && ChosenDecl)
5789 Diag(ChosenDecl->getLocation(), PrevNote)
5790 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5792 // Add any extra diagnostics.
5793 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5794 Diag(Correction.getCorrectionRange().getBegin(), PD);
5797 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5798 TypoDiagnosticGenerator TDG,
5799 TypoRecoveryCallback TRC,
5800 SourceLocation TypoLoc) {
5801 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5802 auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);
5803 auto &State = DelayedTypos[TE];
5804 State.Consumer = std::move(TCC);
5805 State.DiagHandler = std::move(TDG);
5806 State.RecoveryHandler = std::move(TRC);
5807 if (TE)
5808 TypoExprs.push_back(TE);
5809 return TE;
5812 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5813 auto Entry = DelayedTypos.find(TE);
5814 assert(Entry != DelayedTypos.end() &&
5815 "Failed to get the state for a TypoExpr!");
5816 return Entry->second;
5819 void Sema::clearDelayedTypo(TypoExpr *TE) {
5820 DelayedTypos.erase(TE);
5823 void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5824 DeclarationNameInfo Name(II, IILoc);
5825 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5826 R.suppressDiagnostics();
5827 R.setHideTags(false);
5828 LookupName(R, S);
5829 R.dump();