clang 19.0.0git
SemaLookup.cpp
Go to the documentation of this file.
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++.
11//
12//===----------------------------------------------------------------------===//
13
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
29#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Overload.h"
33#include "clang/Sema/Scope.h"
35#include "clang/Sema/Sema.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/TinyPtrVector.h"
43#include "llvm/ADT/edit_distance.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/ErrorHandling.h"
46#include <algorithm>
47#include <iterator>
48#include <list>
49#include <optional>
50#include <set>
51#include <utility>
52#include <vector>
53
54#include "OpenCLBuiltins.inc"
55
56using namespace clang;
57using namespace sema;
58
59namespace {
60 class UnqualUsingEntry {
61 const DeclContext *Nominated;
62 const DeclContext *CommonAncestor;
63
64 public:
65 UnqualUsingEntry(const DeclContext *Nominated,
66 const DeclContext *CommonAncestor)
67 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
68 }
69
70 const DeclContext *getCommonAncestor() const {
71 return CommonAncestor;
72 }
73
74 const DeclContext *getNominatedNamespace() const {
75 return Nominated;
76 }
77
78 // Sort by the pointer value of the common ancestor.
79 struct Comparator {
80 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
81 return L.getCommonAncestor() < R.getCommonAncestor();
82 }
83
84 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
85 return E.getCommonAncestor() < DC;
86 }
87
88 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
89 return DC < E.getCommonAncestor();
90 }
91 };
92 };
93
94 /// A collection of using directives, as used by C++ unqualified
95 /// lookup.
96 class UnqualUsingDirectiveSet {
97 Sema &SemaRef;
98
100
101 ListTy list;
103
104 public:
105 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
106
107 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
108 // C++ [namespace.udir]p1:
109 // During unqualified name lookup, the names appear as if they
110 // were declared in the nearest enclosing namespace which contains
111 // both the using-directive and the nominated namespace.
112 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
113 assert(InnermostFileDC && InnermostFileDC->isFileContext());
114
115 for (; S; S = S->getParent()) {
116 // C++ [namespace.udir]p1:
117 // A using-directive shall not appear in class scope, but may
118 // appear in namespace scope or in block scope.
119 DeclContext *Ctx = S->getEntity();
120 if (Ctx && Ctx->isFileContext()) {
121 visit(Ctx, Ctx);
122 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
123 for (auto *I : S->using_directives())
124 if (SemaRef.isVisible(I))
125 visit(I, InnermostFileDC);
126 }
127 }
128 }
129
130 // Visits a context and collect all of its using directives
131 // recursively. Treats all using directives as if they were
132 // declared in the context.
133 //
134 // A given context is only every visited once, so it is important
135 // that contexts be visited from the inside out in order to get
136 // the effective DCs right.
137 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
138 if (!visited.insert(DC).second)
139 return;
140
141 addUsingDirectives(DC, EffectiveDC);
142 }
143
144 // Visits a using directive and collects all of its using
145 // directives recursively. Treats all using directives as if they
146 // were declared in the effective DC.
147 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
149 if (!visited.insert(NS).second)
150 return;
151
152 addUsingDirective(UD, EffectiveDC);
153 addUsingDirectives(NS, EffectiveDC);
154 }
155
156 // Adds all the using directives in a context (and those nominated
157 // by its using directives, transitively) as if they appeared in
158 // the given effective context.
159 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
161 while (true) {
162 for (auto *UD : DC->using_directives()) {
164 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
165 addUsingDirective(UD, EffectiveDC);
166 queue.push_back(NS);
167 }
168 }
169
170 if (queue.empty())
171 return;
172
173 DC = queue.pop_back_val();
174 }
175 }
176
177 // Add a using directive as if it had been declared in the given
178 // context. This helps implement C++ [namespace.udir]p3:
179 // The using-directive is transitive: if a scope contains a
180 // using-directive that nominates a second namespace that itself
181 // contains using-directives, the effect is as if the
182 // using-directives from the second namespace also appeared in
183 // the first.
184 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
185 // Find the common ancestor between the effective context and
186 // the nominated namespace.
187 DeclContext *Common = UD->getNominatedNamespace();
188 while (!Common->Encloses(EffectiveDC))
189 Common = Common->getParent();
190 Common = Common->getPrimaryContext();
191
192 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
193 }
194
195 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
196
197 typedef ListTy::const_iterator const_iterator;
198
199 const_iterator begin() const { return list.begin(); }
200 const_iterator end() const { return list.end(); }
201
202 llvm::iterator_range<const_iterator>
203 getNamespacesFor(const DeclContext *DC) const {
204 return llvm::make_range(std::equal_range(begin(), end(),
205 DC->getPrimaryContext(),
206 UnqualUsingEntry::Comparator()));
207 }
208 };
209} // end anonymous namespace
210
211// Retrieve the set of identifier namespaces that correspond to a
212// specific kind of name lookup.
213static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
214 bool CPlusPlus,
215 bool Redeclaration) {
216 unsigned IDNS = 0;
217 switch (NameKind) {
223 IDNS = Decl::IDNS_Ordinary;
224 if (CPlusPlus) {
226 if (Redeclaration)
228 }
229 if (Redeclaration)
231 break;
232
234 // Operator lookup is its own crazy thing; it is not the same
235 // as (e.g.) looking up an operator name for redeclaration.
236 assert(!Redeclaration && "cannot do redeclaration operator lookup");
238 break;
239
241 if (CPlusPlus) {
242 IDNS = Decl::IDNS_Type;
243
244 // When looking for a redeclaration of a tag name, we add:
245 // 1) TagFriend to find undeclared friend decls
246 // 2) Namespace because they can't "overload" with tag decls.
247 // 3) Tag because it includes class templates, which can't
248 // "overload" with tag decls.
249 if (Redeclaration)
251 } else {
252 IDNS = Decl::IDNS_Tag;
253 }
254 break;
255
257 IDNS = Decl::IDNS_Label;
258 break;
259
261 IDNS = Decl::IDNS_Member;
262 if (CPlusPlus)
264 break;
265
268 break;
269
272 break;
273
275 assert(Redeclaration && "should only be used for redecl lookup");
279 break;
280
283 break;
284
287 break;
288
291 break;
292
297 break;
298 }
299 return IDNS;
300}
301
302void LookupResult::configure() {
303 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
305
306 // If we're looking for one of the allocation or deallocation
307 // operators, make sure that the implicitly-declared new and delete
308 // operators can be found.
309 switch (NameInfo.getName().getCXXOverloadedOperator()) {
310 case OO_New:
311 case OO_Delete:
312 case OO_Array_New:
313 case OO_Array_Delete:
315 break;
316
317 default:
318 break;
319 }
320
321 // Compiler builtins are always visible, regardless of where they end
322 // up being declared.
323 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
324 if (unsigned BuiltinID = Id->getBuiltinID()) {
325 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
326 AllowHidden = true;
327 }
328 }
329}
330
331bool LookupResult::checkDebugAssumptions() const {
332 // This function is never called by NDEBUG builds.
333 assert(ResultKind != NotFound || Decls.size() == 0);
334 assert(ResultKind != Found || Decls.size() == 1);
335 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
336 (Decls.size() == 1 &&
337 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
338 assert(ResultKind != FoundUnresolvedValue || checkUnresolved());
339 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
340 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
341 Ambiguity == AmbiguousBaseSubobjectTypes)));
342 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
343 (Ambiguity == AmbiguousBaseSubobjectTypes ||
344 Ambiguity == AmbiguousBaseSubobjects)));
345 return true;
346}
347
348// Necessary because CXXBasePaths is not complete in Sema.h
349void LookupResult::deletePaths(CXXBasePaths *Paths) {
350 delete Paths;
351}
352
353/// Get a representative context for a declaration such that two declarations
354/// will have the same context if they were found within the same scope.
356 // For function-local declarations, use that function as the context. This
357 // doesn't account for scopes within the function; the caller must deal with
358 // those.
359 if (const DeclContext *DC = D->getLexicalDeclContext();
360 DC->isFunctionOrMethod())
361 return DC;
362
363 // Otherwise, look at the semantic context of the declaration. The
364 // declaration must have been found there.
365 return D->getDeclContext()->getRedeclContext();
366}
367
368/// Determine whether \p D is a better lookup result than \p Existing,
369/// given that they declare the same entity.
371 const NamedDecl *D,
372 const NamedDecl *Existing) {
373 // When looking up redeclarations of a using declaration, prefer a using
374 // shadow declaration over any other declaration of the same entity.
375 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
376 !isa<UsingShadowDecl>(Existing))
377 return true;
378
379 const auto *DUnderlying = D->getUnderlyingDecl();
380 const auto *EUnderlying = Existing->getUnderlyingDecl();
381
382 // If they have different underlying declarations, prefer a typedef over the
383 // original type (this happens when two type declarations denote the same
384 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
385 // might carry additional semantic information, such as an alignment override.
386 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
387 // declaration over a typedef. Also prefer a tag over a typedef for
388 // destructor name lookup because in some contexts we only accept a
389 // class-name in a destructor declaration.
390 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
391 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
392 bool HaveTag = isa<TagDecl>(EUnderlying);
393 bool WantTag =
395 return HaveTag != WantTag;
396 }
397
398 // Pick the function with more default arguments.
399 // FIXME: In the presence of ambiguous default arguments, we should keep both,
400 // so we can diagnose the ambiguity if the default argument is needed.
401 // See C++ [over.match.best]p3.
402 if (const auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
403 const auto *EFD = cast<FunctionDecl>(EUnderlying);
404 unsigned DMin = DFD->getMinRequiredArguments();
405 unsigned EMin = EFD->getMinRequiredArguments();
406 // If D has more default arguments, it is preferred.
407 if (DMin != EMin)
408 return DMin < EMin;
409 // FIXME: When we track visibility for default function arguments, check
410 // that we pick the declaration with more visible default arguments.
411 }
412
413 // Pick the template with more default template arguments.
414 if (const auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
415 const auto *ETD = cast<TemplateDecl>(EUnderlying);
416 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
417 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
418 // If D has more default arguments, it is preferred. Note that default
419 // arguments (and their visibility) is monotonically increasing across the
420 // redeclaration chain, so this is a quick proxy for "is more recent".
421 if (DMin != EMin)
422 return DMin < EMin;
423 // If D has more *visible* default arguments, it is preferred. Note, an
424 // earlier default argument being visible does not imply that a later
425 // default argument is visible, so we can't just check the first one.
426 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
427 I != N; ++I) {
429 ETD->getTemplateParameters()->getParam(I)) &&
431 DTD->getTemplateParameters()->getParam(I)))
432 return true;
433 }
434 }
435
436 // VarDecl can have incomplete array types, prefer the one with more complete
437 // array type.
438 if (const auto *DVD = dyn_cast<VarDecl>(DUnderlying)) {
439 const auto *EVD = cast<VarDecl>(EUnderlying);
440 if (EVD->getType()->isIncompleteType() &&
441 !DVD->getType()->isIncompleteType()) {
442 // Prefer the decl with a more complete type if visible.
443 return S.isVisible(DVD);
444 }
445 return false; // Avoid picking up a newer decl, just because it was newer.
446 }
447
448 // For most kinds of declaration, it doesn't really matter which one we pick.
449 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
450 // If the existing declaration is hidden, prefer the new one. Otherwise,
451 // keep what we've got.
452 return !S.isVisible(Existing);
453 }
454
455 // Pick the newer declaration; it might have a more precise type.
456 for (const Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
457 Prev = Prev->getPreviousDecl())
458 if (Prev == EUnderlying)
459 return true;
460 return false;
461}
462
463/// Determine whether \p D can hide a tag declaration.
464static bool canHideTag(const NamedDecl *D) {
465 // C++ [basic.scope.declarative]p4:
466 // Given a set of declarations in a single declarative region [...]
467 // exactly one declaration shall declare a class name or enumeration name
468 // that is not a typedef name and the other declarations shall all refer to
469 // the same variable, non-static data member, or enumerator, or all refer
470 // to functions and function templates; in this case the class name or
471 // enumeration name is hidden.
472 // C++ [basic.scope.hiding]p2:
473 // A class name or enumeration name can be hidden by the name of a
474 // variable, data member, function, or enumerator declared in the same
475 // scope.
476 // An UnresolvedUsingValueDecl always instantiates to one of these.
477 D = D->getUnderlyingDecl();
478 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
479 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
480 isa<UnresolvedUsingValueDecl>(D);
481}
482
483/// Resolves the result kind of this lookup.
485 unsigned N = Decls.size();
486
487 // Fast case: no possible ambiguity.
488 if (N == 0) {
489 assert(ResultKind == NotFound ||
490 ResultKind == NotFoundInCurrentInstantiation);
491 return;
492 }
493
494 // If there's a single decl, we need to examine it to decide what
495 // kind of lookup this is.
496 if (N == 1) {
497 const NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
498 if (isa<FunctionTemplateDecl>(D))
499 ResultKind = FoundOverloaded;
500 else if (isa<UnresolvedUsingValueDecl>(D))
501 ResultKind = FoundUnresolvedValue;
502 return;
503 }
504
505 // Don't do any extra resolution if we've already resolved as ambiguous.
506 if (ResultKind == Ambiguous) return;
507
508 llvm::SmallDenseMap<const NamedDecl *, unsigned, 16> Unique;
509 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
510
511 bool Ambiguous = false;
512 bool ReferenceToPlaceHolderVariable = false;
513 bool HasTag = false, HasFunction = false;
514 bool HasFunctionTemplate = false, HasUnresolved = false;
515 const NamedDecl *HasNonFunction = nullptr;
516
517 llvm::SmallVector<const NamedDecl *, 4> EquivalentNonFunctions;
518 llvm::BitVector RemovedDecls(N);
519
520 for (unsigned I = 0; I < N; I++) {
521 const NamedDecl *D = Decls[I]->getUnderlyingDecl();
522 D = cast<NamedDecl>(D->getCanonicalDecl());
523
524 // Ignore an invalid declaration unless it's the only one left.
525 // Also ignore HLSLBufferDecl which not have name conflict with other Decls.
526 if ((D->isInvalidDecl() || isa<HLSLBufferDecl>(D)) &&
527 N - RemovedDecls.count() > 1) {
528 RemovedDecls.set(I);
529 continue;
530 }
531
532 // C++ [basic.scope.hiding]p2:
533 // A class name or enumeration name can be hidden by the name of
534 // an object, function, or enumerator declared in the same
535 // scope. If a class or enumeration name and an object, function,
536 // or enumerator are declared in the same scope (in any order)
537 // with the same name, the class or enumeration name is hidden
538 // wherever the object, function, or enumerator name is visible.
539 if (HideTags && isa<TagDecl>(D)) {
540 bool Hidden = false;
541 for (auto *OtherDecl : Decls) {
542 if (canHideTag(OtherDecl) && !OtherDecl->isInvalidDecl() &&
543 getContextForScopeMatching(OtherDecl)->Equals(
544 getContextForScopeMatching(Decls[I]))) {
545 RemovedDecls.set(I);
546 Hidden = true;
547 break;
548 }
549 }
550 if (Hidden)
551 continue;
552 }
553
554 std::optional<unsigned> ExistingI;
555
556 // Redeclarations of types via typedef can occur both within a scope
557 // and, through using declarations and directives, across scopes. There is
558 // no ambiguity if they all refer to the same type, so unique based on the
559 // canonical type.
560 if (const auto *TD = dyn_cast<TypeDecl>(D)) {
562 auto UniqueResult = UniqueTypes.insert(
563 std::make_pair(getSema().Context.getCanonicalType(T), I));
564 if (!UniqueResult.second) {
565 // The type is not unique.
566 ExistingI = UniqueResult.first->second;
567 }
568 }
569
570 // For non-type declarations, check for a prior lookup result naming this
571 // canonical declaration.
572 if (!D->isPlaceholderVar(getSema().getLangOpts()) && !ExistingI) {
573 auto UniqueResult = Unique.insert(std::make_pair(D, I));
574 if (!UniqueResult.second) {
575 // We've seen this entity before.
576 ExistingI = UniqueResult.first->second;
577 }
578 }
579
580 if (ExistingI) {
581 // This is not a unique lookup result. Pick one of the results and
582 // discard the other.
584 Decls[*ExistingI]))
585 Decls[*ExistingI] = Decls[I];
586 RemovedDecls.set(I);
587 continue;
588 }
589
590 // Otherwise, do some decl type analysis and then continue.
591
592 if (isa<UnresolvedUsingValueDecl>(D)) {
593 HasUnresolved = true;
594 } else if (isa<TagDecl>(D)) {
595 if (HasTag)
596 Ambiguous = true;
597 HasTag = true;
598 } else if (isa<FunctionTemplateDecl>(D)) {
599 HasFunction = true;
600 HasFunctionTemplate = true;
601 } else if (isa<FunctionDecl>(D)) {
602 HasFunction = true;
603 } else {
604 if (HasNonFunction) {
605 // If we're about to create an ambiguity between two declarations that
606 // are equivalent, but one is an internal linkage declaration from one
607 // module and the other is an internal linkage declaration from another
608 // module, just skip it.
609 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
610 D)) {
611 EquivalentNonFunctions.push_back(D);
612 RemovedDecls.set(I);
613 continue;
614 }
615 if (D->isPlaceholderVar(getSema().getLangOpts()) &&
617 getContextForScopeMatching(Decls[I])) {
618 ReferenceToPlaceHolderVariable = true;
619 }
620 Ambiguous = true;
621 }
622 HasNonFunction = D;
623 }
624 }
625
626 // FIXME: This diagnostic should really be delayed until we're done with
627 // the lookup result, in case the ambiguity is resolved by the caller.
628 if (!EquivalentNonFunctions.empty() && !Ambiguous)
630 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
631
632 // Remove decls by replacing them with decls from the end (which
633 // means that we need to iterate from the end) and then truncating
634 // to the new size.
635 for (int I = RemovedDecls.find_last(); I >= 0; I = RemovedDecls.find_prev(I))
636 Decls[I] = Decls[--N];
637 Decls.truncate(N);
638
639 if ((HasNonFunction && (HasFunction || HasUnresolved)) ||
640 (HideTags && HasTag && (HasFunction || HasNonFunction || HasUnresolved)))
641 Ambiguous = true;
642
643 if (Ambiguous && ReferenceToPlaceHolderVariable)
645 else if (Ambiguous)
647 else if (HasUnresolved)
649 else if (N > 1 || HasFunctionTemplate)
651 else
652 ResultKind = LookupResult::Found;
653}
654
655void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
657 for (I = P.begin(), E = P.end(); I != E; ++I)
658 for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;
659 ++DI)
660 addDecl(*DI);
661}
662
664 Paths = new CXXBasePaths;
665 Paths->swap(P);
666 addDeclsFromBasePaths(*Paths);
667 resolveKind();
668 setAmbiguous(AmbiguousBaseSubobjects);
669}
670
672 Paths = new CXXBasePaths;
673 Paths->swap(P);
674 addDeclsFromBasePaths(*Paths);
675 resolveKind();
676 setAmbiguous(AmbiguousBaseSubobjectTypes);
677}
678
679void LookupResult::print(raw_ostream &Out) {
680 Out << Decls.size() << " result(s)";
681 if (isAmbiguous()) Out << ", ambiguous";
682 if (Paths) Out << ", base paths present";
683
684 for (iterator I = begin(), E = end(); I != E; ++I) {
685 Out << "\n";
686 (*I)->print(Out, 2);
687 }
688}
689
690LLVM_DUMP_METHOD void LookupResult::dump() {
691 llvm::errs() << "lookup results for " << getLookupName().getAsString()
692 << ":\n";
693 for (NamedDecl *D : *this)
694 D->dump();
695}
696
697/// Diagnose a missing builtin type.
698static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,
699 llvm::StringRef Name) {
700 S.Diag(SourceLocation(), diag::err_opencl_type_not_found)
701 << TypeClass << Name;
702 return S.Context.VoidTy;
703}
704
705/// Lookup an OpenCL enum type.
706static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
710 if (Result.empty())
711 return diagOpenCLBuiltinTypeError(S, "enum", Name);
712 EnumDecl *Decl = Result.getAsSingle<EnumDecl>();
713 if (!Decl)
714 return diagOpenCLBuiltinTypeError(S, "enum", Name);
715 return S.Context.getEnumType(Decl);
716}
717
718/// Lookup an OpenCL typedef type.
719static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
723 if (Result.empty())
724 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
725 TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();
726 if (!Decl)
727 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
728 return S.Context.getTypedefType(Decl);
729}
730
731/// Get the QualType instances of the return type and arguments for an OpenCL
732/// builtin function signature.
733/// \param S (in) The Sema instance.
734/// \param OpenCLBuiltin (in) The signature currently handled.
735/// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
736/// type used as return type or as argument.
737/// Only meaningful for generic types, otherwise equals 1.
738/// \param RetTypes (out) List of the possible return types.
739/// \param ArgTypes (out) List of the possible argument types. For each
740/// argument, ArgTypes contains QualTypes for the Cartesian product
741/// of (vector sizes) x (types) .
743 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,
744 SmallVector<QualType, 1> &RetTypes,
746 // Get the QualType instances of the return types.
747 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];
748 OCL2Qual(S, TypeTable[Sig], RetTypes);
749 GenTypeMaxCnt = RetTypes.size();
750
751 // Get the QualType instances of the arguments.
752 // First type is the return type, skip it.
753 for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) {
755 OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
756 Ty);
757 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
758 ArgTypes.push_back(std::move(Ty));
759 }
760}
761
762/// Create a list of the candidate function overloads for an OpenCL builtin
763/// function.
764/// \param Context (in) The ASTContext instance.
765/// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic
766/// type used as return type or as argument.
767/// Only meaningful for generic types, otherwise equals 1.
768/// \param FunctionList (out) List of FunctionTypes.
769/// \param RetTypes (in) List of the possible return types.
770/// \param ArgTypes (in) List of the possible types for the arguments.
772 ASTContext &Context, unsigned GenTypeMaxCnt,
773 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,
776 Context.getDefaultCallingConvention(false, false, true));
777 PI.Variadic = false;
778
779 // Do not attempt to create any FunctionTypes if there are no return types,
780 // which happens when a type belongs to a disabled extension.
781 if (RetTypes.size() == 0)
782 return;
783
784 // Create FunctionTypes for each (gen)type.
785 for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
787
788 for (unsigned A = 0; A < ArgTypes.size(); A++) {
789 // Bail out if there is an argument that has no available types.
790 if (ArgTypes[A].size() == 0)
791 return;
792
793 // Builtins such as "max" have an "sgentype" argument that represents
794 // the corresponding scalar type of a gentype. The number of gentypes
795 // must be a multiple of the number of sgentypes.
796 assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 &&
797 "argument type count not compatible with gentype type count");
798 unsigned Idx = IGenType % ArgTypes[A].size();
799 ArgList.push_back(ArgTypes[A][Idx]);
800 }
801
802 FunctionList.push_back(Context.getFunctionType(
803 RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI));
804 }
805}
806
807/// When trying to resolve a function name, if isOpenCLBuiltin() returns a
808/// non-null <Index, Len> pair, then the name is referencing an OpenCL
809/// builtin function. Add all candidate signatures to the LookUpResult.
810///
811/// \param S (in) The Sema instance.
812/// \param LR (inout) The LookupResult instance.
813/// \param II (in) The identifier being resolved.
814/// \param FctIndex (in) Starting index in the BuiltinTable.
815/// \param Len (in) The signature list has Len elements.
817 IdentifierInfo *II,
818 const unsigned FctIndex,
819 const unsigned Len) {
820 // The builtin function declaration uses generic types (gentype).
821 bool HasGenType = false;
822
823 // Maximum number of types contained in a generic type used as return type or
824 // as argument. Only meaningful for generic types, otherwise equals 1.
825 unsigned GenTypeMaxCnt;
826
827 ASTContext &Context = S.Context;
828
829 for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {
830 const OpenCLBuiltinStruct &OpenCLBuiltin =
831 BuiltinTable[FctIndex + SignatureIndex];
832
833 // Ignore this builtin function if it is not available in the currently
834 // selected language version.
835 if (!isOpenCLVersionContainedInMask(Context.getLangOpts(),
836 OpenCLBuiltin.Versions))
837 continue;
838
839 // Ignore this builtin function if it carries an extension macro that is
840 // not defined. This indicates that the extension is not supported by the
841 // target, so the builtin function should not be available.
842 StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];
843 if (!Extensions.empty()) {
845 Extensions.split(ExtVec, " ");
846 bool AllExtensionsDefined = true;
847 for (StringRef Ext : ExtVec) {
848 if (!S.getPreprocessor().isMacroDefined(Ext)) {
849 AllExtensionsDefined = false;
850 break;
851 }
852 }
853 if (!AllExtensionsDefined)
854 continue;
855 }
856
859
860 // Obtain QualType lists for the function signature.
861 GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,
862 ArgTypes);
863 if (GenTypeMaxCnt > 1) {
864 HasGenType = true;
865 }
866
867 // Create function overload for each type combination.
868 std::vector<QualType> FunctionList;
869 GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,
870 ArgTypes);
871
874 FunctionDecl *NewOpenCLBuiltin;
875
876 for (const auto &FTy : FunctionList) {
877 NewOpenCLBuiltin = FunctionDecl::Create(
878 Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,
880 FTy->isFunctionProtoType());
881 NewOpenCLBuiltin->setImplicit();
882
883 // Create Decl objects for each parameter, adding them to the
884 // FunctionDecl.
885 const auto *FP = cast<FunctionProtoType>(FTy);
887 for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
889 Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(),
890 nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr);
891 Parm->setScopeInfo(0, IParm);
892 ParmList.push_back(Parm);
893 }
894 NewOpenCLBuiltin->setParams(ParmList);
895
896 // Add function attributes.
897 if (OpenCLBuiltin.IsPure)
898 NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context));
899 if (OpenCLBuiltin.IsConst)
900 NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context));
901 if (OpenCLBuiltin.IsConv)
902 NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context));
903
904 if (!S.getLangOpts().OpenCLCPlusPlus)
905 NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context));
906
907 LR.addDecl(NewOpenCLBuiltin);
908 }
909 }
910
911 // If we added overloads, need to resolve the lookup result.
912 if (Len > 1 || HasGenType)
913 LR.resolveKind();
914}
915
916/// Lookup a builtin function, when name lookup would otherwise
917/// fail.
919 Sema::LookupNameKind NameKind = R.getLookupKind();
920
921 // If we didn't find a use of this identifier, and if the identifier
922 // corresponds to a compiler builtin, create the decl object for the builtin
923 // now, injecting it into translation unit scope, and return it.
924 if (NameKind == Sema::LookupOrdinaryName ||
927 if (II) {
928 if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
929 if (II == getASTContext().getMakeIntegerSeqName()) {
930 R.addDecl(getASTContext().getMakeIntegerSeqDecl());
931 return true;
932 } else if (II == getASTContext().getTypePackElementName()) {
933 R.addDecl(getASTContext().getTypePackElementDecl());
934 return true;
935 }
936 }
937
938 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
939 if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {
940 auto Index = isOpenCLBuiltin(II->getName());
941 if (Index.first) {
942 InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1,
943 Index.second);
944 return true;
945 }
946 }
947
949 if (!RVIntrinsicManager)
950 RVIntrinsicManager = CreateRISCVIntrinsicManager(*this);
951
952 RVIntrinsicManager->InitIntrinsicList();
953
954 if (RVIntrinsicManager->CreateIntrinsicIfFound(R, II, PP))
955 return true;
956 }
957
958 // If this is a builtin on this (or all) targets, create the decl.
959 if (unsigned BuiltinID = II->getBuiltinID()) {
960 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
961 // library functions like 'malloc'. Instead, we'll just error.
964 return false;
965
966 if (NamedDecl *D =
967 LazilyCreateBuiltin(II, BuiltinID, TUScope,
968 R.isForRedeclaration(), R.getNameLoc())) {
969 R.addDecl(D);
970 return true;
971 }
972 }
973 }
974 }
975
976 return false;
977}
978
979/// Looks up the declaration of "struct objc_super" and
980/// saves it for later use in building builtin declaration of
981/// objc_msgSendSuper and objc_msgSendSuper_stret.
983 ASTContext &Context = Sema.Context;
984 LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),
987 if (Result.getResultKind() == LookupResult::Found)
988 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
989 Context.setObjCSuperType(Context.getTagDeclType(TD));
990}
991
993 if (ID == Builtin::BIobjc_msgSendSuper)
995}
996
997/// Determine whether we can declare a special member function within
998/// the class at this point.
1000 // We need to have a definition for the class.
1001 if (!Class->getDefinition() || Class->isDependentContext())
1002 return false;
1003
1004 // We can't be in the middle of defining the class.
1005 return !Class->isBeingDefined();
1006}
1007
1010 return;
1011
1012 // If the default constructor has not yet been declared, do so now.
1013 if (Class->needsImplicitDefaultConstructor())
1015
1016 // If the copy constructor has not yet been declared, do so now.
1017 if (Class->needsImplicitCopyConstructor())
1019
1020 // If the copy assignment operator has not yet been declared, do so now.
1021 if (Class->needsImplicitCopyAssignment())
1023
1024 if (getLangOpts().CPlusPlus11) {
1025 // If the move constructor has not yet been declared, do so now.
1026 if (Class->needsImplicitMoveConstructor())
1028
1029 // If the move assignment operator has not yet been declared, do so now.
1030 if (Class->needsImplicitMoveAssignment())
1032 }
1033
1034 // If the destructor has not yet been declared, do so now.
1035 if (Class->needsImplicitDestructor())
1037}
1038
1039/// Determine whether this is the name of an implicitly-declared
1040/// special member function.
1042 switch (Name.getNameKind()) {
1045 return true;
1046
1048 return Name.getCXXOverloadedOperator() == OO_Equal;
1049
1050 default:
1051 break;
1052 }
1053
1054 return false;
1055}
1056
1057/// If there are any implicit member functions with the given name
1058/// that need to be declared in the given declaration context, do so.
1060 DeclarationName Name,
1062 const DeclContext *DC) {
1063 if (!DC)
1064 return;
1065
1066 switch (Name.getNameKind()) {
1068 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1069 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1070 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1071 if (Record->needsImplicitDefaultConstructor())
1073 if (Record->needsImplicitCopyConstructor())
1075 if (S.getLangOpts().CPlusPlus11 &&
1076 Record->needsImplicitMoveConstructor())
1078 }
1079 break;
1080
1082 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1083 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
1086 break;
1087
1089 if (Name.getCXXOverloadedOperator() != OO_Equal)
1090 break;
1091
1092 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
1093 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1094 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1095 if (Record->needsImplicitCopyAssignment())
1097 if (S.getLangOpts().CPlusPlus11 &&
1098 Record->needsImplicitMoveAssignment())
1100 }
1101 }
1102 break;
1103
1105 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
1106 break;
1107
1108 default:
1109 break;
1110 }
1111}
1112
1113// Adds all qualifying matches for a name within a decl context to the
1114// given lookup result. Returns true if any matches were found.
1115static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
1116 bool Found = false;
1117
1118 // Lazily declare C++ special member functions.
1119 if (S.getLangOpts().CPlusPlus)
1121 DC);
1122
1123 // Perform lookup into this declaration context.
1125 for (NamedDecl *D : DR) {
1126 if ((D = R.getAcceptableDecl(D))) {
1127 R.addDecl(D);
1128 Found = true;
1129 }
1130 }
1131
1132 if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))
1133 return true;
1134
1135 if (R.getLookupName().getNameKind()
1138 !isa<CXXRecordDecl>(DC))
1139 return Found;
1140
1141 // C++ [temp.mem]p6:
1142 // A specialization of a conversion function template is not found by
1143 // name lookup. Instead, any conversion function templates visible in the
1144 // context of the use are considered. [...]
1145 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1146 if (!Record->isCompleteDefinition())
1147 return Found;
1148
1149 // For conversion operators, 'operator auto' should only match
1150 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
1151 // as a candidate for template substitution.
1152 auto *ContainedDeducedType =
1154 if (R.getLookupName().getNameKind() ==
1156 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
1157 return Found;
1158
1159 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
1160 UEnd = Record->conversion_end(); U != UEnd; ++U) {
1161 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
1162 if (!ConvTemplate)
1163 continue;
1164
1165 // When we're performing lookup for the purposes of redeclaration, just
1166 // add the conversion function template. When we deduce template
1167 // arguments for specializations, we'll end up unifying the return
1168 // type of the new declaration with the type of the function template.
1169 if (R.isForRedeclaration()) {
1170 R.addDecl(ConvTemplate);
1171 Found = true;
1172 continue;
1173 }
1174
1175 // C++ [temp.mem]p6:
1176 // [...] For each such operator, if argument deduction succeeds
1177 // (14.9.2.3), the resulting specialization is used as if found by
1178 // name lookup.
1179 //
1180 // When referencing a conversion function for any purpose other than
1181 // a redeclaration (such that we'll be building an expression with the
1182 // result), perform template argument deduction and place the
1183 // specialization into the result set. We do this to avoid forcing all
1184 // callers to perform special deduction for conversion functions.
1186 FunctionDecl *Specialization = nullptr;
1187
1188 const FunctionProtoType *ConvProto
1189 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
1190 assert(ConvProto && "Nonsensical conversion function template type");
1191
1192 // Compute the type of the function that we would expect the conversion
1193 // function to have, if it were to match the name given.
1194 // FIXME: Calling convention!
1197 EPI.ExceptionSpec = EST_None;
1199 R.getLookupName().getCXXNameType(), std::nullopt, EPI);
1200
1201 // Perform template argument deduction against the type that we would
1202 // expect the function to have.
1203 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
1204 Specialization, Info) ==
1207 Found = true;
1208 }
1209 }
1210
1211 return Found;
1212}
1213
1214// Performs C++ unqualified lookup into the given file context.
1215static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
1216 const DeclContext *NS,
1217 UnqualUsingDirectiveSet &UDirs) {
1218
1219 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
1220
1221 // Perform direct name lookup into the LookupCtx.
1222 bool Found = LookupDirect(S, R, NS);
1223
1224 // Perform direct name lookup into the namespaces nominated by the
1225 // using directives whose common ancestor is this namespace.
1226 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
1227 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
1228 Found = true;
1229
1230 R.resolveKind();
1231
1232 return Found;
1233}
1234
1236 if (DeclContext *Ctx = S->getEntity())
1237 return Ctx->isFileContext();
1238 return false;
1239}
1240
1241/// Find the outer declaration context from this scope. This indicates the
1242/// context that we should search up to (exclusive) before considering the
1243/// parent of the specified scope.
1245 for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())
1246 if (DeclContext *DC = OuterS->getLookupEntity())
1247 return DC;
1248 return nullptr;
1249}
1250
1251namespace {
1252/// An RAII object to specify that we want to find block scope extern
1253/// declarations.
1254struct FindLocalExternScope {
1255 FindLocalExternScope(LookupResult &R)
1256 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1257 Decl::IDNS_LocalExtern) {
1260 }
1261 void restore() {
1262 R.setFindLocalExtern(OldFindLocalExtern);
1263 }
1264 ~FindLocalExternScope() {
1265 restore();
1266 }
1267 LookupResult &R;
1268 bool OldFindLocalExtern;
1269};
1270} // end anonymous namespace
1271
1272bool Sema::CppLookupName(LookupResult &R, Scope *S) {
1273 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
1274
1275 DeclarationName Name = R.getLookupName();
1276 Sema::LookupNameKind NameKind = R.getLookupKind();
1277
1278 // If this is the name of an implicitly-declared special member function,
1279 // go through the scope stack to implicitly declare
1281 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1282 if (DeclContext *DC = PreS->getEntity())
1284 }
1285
1286 // C++23 [temp.dep.general]p2:
1287 // The component name of an unqualified-id is dependent if
1288 // - it is a conversion-function-id whose conversion-type-id
1289 // is dependent, or
1290 // - it is operator= and the current class is a templated entity, or
1291 // - the unqualified-id is the postfix-expression in a dependent call.
1292 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1293 Name.getCXXNameType()->isDependentType()) {
1295 return false;
1296 }
1297
1298 // Implicitly declare member functions with the name we're looking for, if in
1299 // fact we are in a scope where it matters.
1300
1301 Scope *Initial = S;
1303 I = IdResolver.begin(Name),
1304 IEnd = IdResolver.end();
1305
1306 // First we lookup local scope.
1307 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1308 // ...During unqualified name lookup (3.4.1), the names appear as if
1309 // they were declared in the nearest enclosing namespace which contains
1310 // both the using-directive and the nominated namespace.
1311 // [Note: in this context, "contains" means "contains directly or
1312 // indirectly".
1313 //
1314 // For example:
1315 // namespace A { int i; }
1316 // void foo() {
1317 // int i;
1318 // {
1319 // using namespace A;
1320 // ++i; // finds local 'i', A::i appears at global scope
1321 // }
1322 // }
1323 //
1324 UnqualUsingDirectiveSet UDirs(*this);
1325 bool VisitedUsingDirectives = false;
1326 bool LeftStartingScope = false;
1327
1328 // When performing a scope lookup, we want to find local extern decls.
1329 FindLocalExternScope FindLocals(R);
1330
1331 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1332 bool SearchNamespaceScope = true;
1333 // Check whether the IdResolver has anything in this scope.
1334 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1335 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1336 if (NameKind == LookupRedeclarationWithLinkage &&
1337 !(*I)->isTemplateParameter()) {
1338 // If it's a template parameter, we still find it, so we can diagnose
1339 // the invalid redeclaration.
1340
1341 // Determine whether this (or a previous) declaration is
1342 // out-of-scope.
1343 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1344 LeftStartingScope = true;
1345
1346 // If we found something outside of our starting scope that
1347 // does not have linkage, skip it.
1348 if (LeftStartingScope && !((*I)->hasLinkage())) {
1349 R.setShadowed();
1350 continue;
1351 }
1352 } else {
1353 // We found something in this scope, we should not look at the
1354 // namespace scope
1355 SearchNamespaceScope = false;
1356 }
1357 R.addDecl(ND);
1358 }
1359 }
1360 if (!SearchNamespaceScope) {
1361 R.resolveKind();
1362 if (S->isClassScope())
1363 if (auto *Record = dyn_cast_if_present<CXXRecordDecl>(S->getEntity()))
1365 return true;
1366 }
1367
1368 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1369 // C++11 [class.friend]p11:
1370 // If a friend declaration appears in a local class and the name
1371 // specified is an unqualified name, a prior declaration is
1372 // looked up without considering scopes that are outside the
1373 // innermost enclosing non-class scope.
1374 return false;
1375 }
1376
1377 if (DeclContext *Ctx = S->getLookupEntity()) {
1378 DeclContext *OuterCtx = findOuterContext(S);
1379 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1380 // We do not directly look into transparent contexts, since
1381 // those entities will be found in the nearest enclosing
1382 // non-transparent context.
1383 if (Ctx->isTransparentContext())
1384 continue;
1385
1386 // We do not look directly into function or method contexts,
1387 // since all of the local variables and parameters of the
1388 // function/method are present within the Scope.
1389 if (Ctx->isFunctionOrMethod()) {
1390 // If we have an Objective-C instance method, look for ivars
1391 // in the corresponding interface.
1392 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1393 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1394 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1395 ObjCInterfaceDecl *ClassDeclared;
1396 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1397 Name.getAsIdentifierInfo(),
1398 ClassDeclared)) {
1399 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1400 R.addDecl(ND);
1401 R.resolveKind();
1402 return true;
1403 }
1404 }
1405 }
1406 }
1407
1408 continue;
1409 }
1410
1411 // If this is a file context, we need to perform unqualified name
1412 // lookup considering using directives.
1413 if (Ctx->isFileContext()) {
1414 // If we haven't handled using directives yet, do so now.
1415 if (!VisitedUsingDirectives) {
1416 // Add using directives from this context up to the top level.
1417 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1418 if (UCtx->isTransparentContext())
1419 continue;
1420
1421 UDirs.visit(UCtx, UCtx);
1422 }
1423
1424 // Find the innermost file scope, so we can add using directives
1425 // from local scopes.
1426 Scope *InnermostFileScope = S;
1427 while (InnermostFileScope &&
1428 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1429 InnermostFileScope = InnermostFileScope->getParent();
1430 UDirs.visitScopeChain(Initial, InnermostFileScope);
1431
1432 UDirs.done();
1433
1434 VisitedUsingDirectives = true;
1435 }
1436
1437 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1438 R.resolveKind();
1439 return true;
1440 }
1441
1442 continue;
1443 }
1444
1445 // Perform qualified name lookup into this context.
1446 // FIXME: In some cases, we know that every name that could be found by
1447 // this qualified name lookup will also be on the identifier chain. For
1448 // example, inside a class without any base classes, we never need to
1449 // perform qualified lookup because all of the members are on top of the
1450 // identifier chain.
1451 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1452 return true;
1453 }
1454 }
1455 }
1456
1457 // Stop if we ran out of scopes.
1458 // FIXME: This really, really shouldn't be happening.
1459 if (!S) return false;
1460
1461 // If we are looking for members, no need to look into global/namespace scope.
1462 if (NameKind == LookupMemberName)
1463 return false;
1464
1465 // Collect UsingDirectiveDecls in all scopes, and recursively all
1466 // nominated namespaces by those using-directives.
1467 //
1468 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1469 // don't build it for each lookup!
1470 if (!VisitedUsingDirectives) {
1471 UDirs.visitScopeChain(Initial, S);
1472 UDirs.done();
1473 }
1474
1475 // If we're not performing redeclaration lookup, do not look for local
1476 // extern declarations outside of a function scope.
1477 if (!R.isForRedeclaration())
1478 FindLocals.restore();
1479
1480 // Lookup namespace scope, and global scope.
1481 // Unqualified name lookup in C++ requires looking into scopes
1482 // that aren't strictly lexical, and therefore we walk through the
1483 // context as well as walking through the scopes.
1484 for (; S; S = S->getParent()) {
1485 // Check whether the IdResolver has anything in this scope.
1486 bool Found = false;
1487 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1488 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1489 // We found something. Look for anything else in our scope
1490 // with this same name and in an acceptable identifier
1491 // namespace, so that we can construct an overload set if we
1492 // need to.
1493 Found = true;
1494 R.addDecl(ND);
1495 }
1496 }
1497
1498 if (Found && S->isTemplateParamScope()) {
1499 R.resolveKind();
1500 return true;
1501 }
1502
1503 DeclContext *Ctx = S->getLookupEntity();
1504 if (Ctx) {
1505 DeclContext *OuterCtx = findOuterContext(S);
1506 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1507 // We do not directly look into transparent contexts, since
1508 // those entities will be found in the nearest enclosing
1509 // non-transparent context.
1510 if (Ctx->isTransparentContext())
1511 continue;
1512
1513 // If we have a context, and it's not a context stashed in the
1514 // template parameter scope for an out-of-line definition, also
1515 // look into that context.
1516 if (!(Found && S->isTemplateParamScope())) {
1517 assert(Ctx->isFileContext() &&
1518 "We should have been looking only at file context here already.");
1519
1520 // Look into context considering using-directives.
1521 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1522 Found = true;
1523 }
1524
1525 if (Found) {
1526 R.resolveKind();
1527 return true;
1528 }
1529
1530 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1531 return false;
1532 }
1533 }
1534
1535 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1536 return false;
1537 }
1538
1539 return !R.empty();
1540}
1541
1543 if (auto *M = getCurrentModule())
1545 else
1546 // We're not building a module; just make the definition visible.
1548
1549 // If ND is a template declaration, make the template parameters
1550 // visible too. They're not (necessarily) within a mergeable DeclContext.
1551 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1552 for (auto *Param : *TD->getTemplateParameters())
1554}
1555
1556/// Find the module in which the given declaration was defined.
1557static Module *getDefiningModule(Sema &S, Decl *Entity) {
1558 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1559 // If this function was instantiated from a template, the defining module is
1560 // the module containing the pattern.
1561 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1562 Entity = Pattern;
1563 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1565 Entity = Pattern;
1566 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1567 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1568 Entity = Pattern;
1569 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1570 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1571 Entity = Pattern;
1572 }
1573
1574 // Walk up to the containing context. That might also have been instantiated
1575 // from a template.
1576 DeclContext *Context = Entity->getLexicalDeclContext();
1577 if (Context->isFileContext())
1578 return S.getOwningModule(Entity);
1579 return getDefiningModule(S, cast<Decl>(Context));
1580}
1581
1583 unsigned N = CodeSynthesisContexts.size();
1584 for (unsigned I = CodeSynthesisContextLookupModules.size();
1585 I != N; ++I) {
1586 Module *M = CodeSynthesisContexts[I].Entity ?
1587 getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
1588 nullptr;
1589 if (M && !LookupModulesCache.insert(M).second)
1590 M = nullptr;
1592 }
1593 return LookupModulesCache;
1594}
1595
1596/// Determine if we could use all the declarations in the module.
1597bool Sema::isUsableModule(const Module *M) {
1598 assert(M && "We shouldn't check nullness for module here");
1599 // Return quickly if we cached the result.
1600 if (UsableModuleUnitsCache.count(M))
1601 return true;
1602
1603 // If M is the global module fragment of the current translation unit. So it
1604 // should be usable.
1605 // [module.global.frag]p1:
1606 // The global module fragment can be used to provide declarations that are
1607 // attached to the global module and usable within the module unit.
1608 if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment ||
1609 // If M is the module we're parsing, it should be usable. This covers the
1610 // private module fragment. The private module fragment is usable only if
1611 // it is within the current module unit. And it must be the current
1612 // parsing module unit if it is within the current module unit according
1613 // to the grammar of the private module fragment. NOTE: This is covered by
1614 // the following condition. The intention of the check is to avoid string
1615 // comparison as much as possible.
1616 M == getCurrentModule() ||
1617 // The module unit which is in the same module with the current module
1618 // unit is usable.
1619 //
1620 // FIXME: Here we judge if they are in the same module by comparing the
1621 // string. Is there any better solution?
1623 llvm::StringRef(getLangOpts().CurrentModule).split(':').first) {
1624 UsableModuleUnitsCache.insert(M);
1625 return true;
1626 }
1627
1628 return false;
1629}
1630
1632 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1633 if (isModuleVisible(Merged))
1634 return true;
1635 return false;
1636}
1637
1639 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1640 if (isUsableModule(Merged))
1641 return true;
1642 return false;
1643}
1644
1645template <typename ParmDecl>
1646static bool
1649 Sema::AcceptableKind Kind) {
1650 if (!D->hasDefaultArgument())
1651 return false;
1652
1654 while (D && Visited.insert(D).second) {
1655 auto &DefaultArg = D->getDefaultArgStorage();
1656 if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))
1657 return true;
1658
1659 if (!DefaultArg.isInherited() && Modules) {
1660 auto *NonConstD = const_cast<ParmDecl*>(D);
1661 Modules->push_back(S.getOwningModule(NonConstD));
1662 }
1663
1664 // If there was a previous default argument, maybe its parameter is
1665 // acceptable.
1666 D = DefaultArg.getInheritedFrom();
1667 }
1668 return false;
1669}
1670
1672 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,
1673 Sema::AcceptableKind Kind) {
1674 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1675 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1676
1677 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1678 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1679
1680 return ::hasAcceptableDefaultArgument(
1681 *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);
1682}
1683
1686 return hasAcceptableDefaultArgument(D, Modules,
1688}
1689
1691 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1692 return hasAcceptableDefaultArgument(D, Modules,
1694}
1695
1696template <typename Filter>
1697static bool
1699 llvm::SmallVectorImpl<Module *> *Modules, Filter F,
1700 Sema::AcceptableKind Kind) {
1701 bool HasFilteredRedecls = false;
1702
1703 for (auto *Redecl : D->redecls()) {
1704 auto *R = cast<NamedDecl>(Redecl);
1705 if (!F(R))
1706 continue;
1707
1708 if (S.isAcceptable(R, Kind))
1709 return true;
1710
1711 HasFilteredRedecls = true;
1712
1713 if (Modules)
1714 Modules->push_back(R->getOwningModule());
1715 }
1716
1717 // Only return false if there is at least one redecl that is not filtered out.
1718 if (HasFilteredRedecls)
1719 return false;
1720
1721 return true;
1722}
1723
1724static bool
1727 Sema::AcceptableKind Kind) {
1729 S, D, Modules,
1730 [](const NamedDecl *D) {
1731 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1732 return RD->getTemplateSpecializationKind() ==
1734 if (auto *FD = dyn_cast<FunctionDecl>(D))
1735 return FD->getTemplateSpecializationKind() ==
1737 if (auto *VD = dyn_cast<VarDecl>(D))
1738 return VD->getTemplateSpecializationKind() ==
1740 llvm_unreachable("unknown explicit specialization kind");
1741 },
1742 Kind);
1743}
1744
1746 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1747 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1749}
1750
1752 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1753 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1755}
1756
1757static bool
1760 Sema::AcceptableKind Kind) {
1761 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1762 "not a member specialization");
1764 S, D, Modules,
1765 [](const NamedDecl *D) {
1766 // If the specialization is declared at namespace scope, then it's a
1767 // member specialization declaration. If it's lexically inside the class
1768 // definition then it was instantiated.
1769 //
1770 // FIXME: This is a hack. There should be a better way to determine
1771 // this.
1772 // FIXME: What about MS-style explicit specializations declared within a
1773 // class definition?
1774 return D->getLexicalDeclContext()->isFileContext();
1775 },
1776 Kind);
1777}
1778
1780 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1781 return hasAcceptableMemberSpecialization(*this, D, Modules,
1783}
1784
1786 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1787 return hasAcceptableMemberSpecialization(*this, D, Modules,
1789}
1790
1791/// Determine whether a declaration is acceptable to name lookup.
1792///
1793/// This routine determines whether the declaration D is acceptable in the
1794/// current lookup context, taking into account the current template
1795/// instantiation stack. During template instantiation, a declaration is
1796/// acceptable if it is acceptable from a module containing any entity on the
1797/// template instantiation path (by instantiating a template, you allow it to
1798/// see the declarations that your module can see, including those later on in
1799/// your module).
1800bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
1801 Sema::AcceptableKind Kind) {
1802 assert(!D->isUnconditionallyVisible() &&
1803 "should not call this: not in slow case");
1804
1805 Module *DeclModule = SemaRef.getOwningModule(D);
1806 assert(DeclModule && "hidden decl has no owning module");
1807
1808 // If the owning module is visible, the decl is acceptable.
1809 if (SemaRef.isModuleVisible(DeclModule,
1811 return true;
1812
1813 // Determine whether a decl context is a file context for the purpose of
1814 // visibility/reachability. This looks through some (export and linkage spec)
1815 // transparent contexts, but not others (enums).
1816 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1817 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1818 isa<ExportDecl>(DC);
1819 };
1820
1821 // If this declaration is not at namespace scope
1822 // then it is acceptable if its lexical parent has a acceptable definition.
1824 if (DC && !IsEffectivelyFileContext(DC)) {
1825 // For a parameter, check whether our current template declaration's
1826 // lexical context is acceptable, not whether there's some other acceptable
1827 // definition of it, because parameters aren't "within" the definition.
1828 //
1829 // In C++ we need to check for a acceptable definition due to ODR merging,
1830 // and in C we must not because each declaration of a function gets its own
1831 // set of declarations for tags in prototype scope.
1832 bool AcceptableWithinParent;
1833 if (D->isTemplateParameter()) {
1834 bool SearchDefinitions = true;
1835 if (const auto *DCD = dyn_cast<Decl>(DC)) {
1836 if (const auto *TD = DCD->getDescribedTemplate()) {
1837 TemplateParameterList *TPL = TD->getTemplateParameters();
1838 auto Index = getDepthAndIndex(D).second;
1839 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1840 }
1841 }
1842 if (SearchDefinitions)
1843 AcceptableWithinParent =
1844 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1845 else
1846 AcceptableWithinParent =
1847 isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1848 } else if (isa<ParmVarDecl>(D) ||
1849 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1850 AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1851 else if (D->isModulePrivate()) {
1852 // A module-private declaration is only acceptable if an enclosing lexical
1853 // parent was merged with another definition in the current module.
1854 AcceptableWithinParent = false;
1855 do {
1856 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1857 AcceptableWithinParent = true;
1858 break;
1859 }
1860 DC = DC->getLexicalParent();
1861 } while (!IsEffectivelyFileContext(DC));
1862 } else {
1863 AcceptableWithinParent =
1864 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1865 }
1866
1867 if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1869 // FIXME: Do something better in this case.
1870 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1871 // Cache the fact that this declaration is implicitly visible because
1872 // its parent has a visible definition.
1874 }
1875 return AcceptableWithinParent;
1876 }
1877
1879 return false;
1880
1881 assert(Kind == Sema::AcceptableKind::Reachable &&
1882 "Additional Sema::AcceptableKind?");
1883 return isReachableSlow(SemaRef, D);
1884}
1885
1886bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1887 // The module might be ordinarily visible. For a module-private query, that
1888 // means it is part of the current module.
1889 if (ModulePrivate && isUsableModule(M))
1890 return true;
1891
1892 // For a query which is not module-private, that means it is in our visible
1893 // module set.
1894 if (!ModulePrivate && VisibleModules.isVisible(M))
1895 return true;
1896
1897 // Otherwise, it might be visible by virtue of the query being within a
1898 // template instantiation or similar that is permitted to look inside M.
1899
1900 // Find the extra places where we need to look.
1901 const auto &LookupModules = getLookupModules();
1902 if (LookupModules.empty())
1903 return false;
1904
1905 // If our lookup set contains the module, it's visible.
1906 if (LookupModules.count(M))
1907 return true;
1908
1909 // The global module fragments are visible to its corresponding module unit.
1910 // So the global module fragment should be visible if the its corresponding
1911 // module unit is visible.
1912 if (M->isGlobalModule() && LookupModules.count(M->getTopLevelModule()))
1913 return true;
1914
1915 // For a module-private query, that's everywhere we get to look.
1916 if (ModulePrivate)
1917 return false;
1918
1919 // Check whether M is transitively exported to an import of the lookup set.
1920 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1921 return LookupM->isModuleVisible(M);
1922 });
1923}
1924
1925// FIXME: Return false directly if we don't have an interface dependency on the
1926// translation unit containing D.
1927bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
1928 assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
1929
1930 Module *DeclModule = SemaRef.getOwningModule(D);
1931 assert(DeclModule && "hidden decl has no owning module");
1932
1933 // Entities in header like modules are reachable only if they're visible.
1934 if (DeclModule->isHeaderLikeModule())
1935 return false;
1936
1937 if (!D->isInAnotherModuleUnit())
1938 return true;
1939
1940 // [module.reach]/p3:
1941 // A declaration D is reachable from a point P if:
1942 // ...
1943 // - D is not discarded ([module.global.frag]), appears in a translation unit
1944 // that is reachable from P, and does not appear within a private module
1945 // fragment.
1946 //
1947 // A declaration that's discarded in the GMF should be module-private.
1948 if (D->isModulePrivate())
1949 return false;
1950
1951 // [module.reach]/p1
1952 // A translation unit U is necessarily reachable from a point P if U is a
1953 // module interface unit on which the translation unit containing P has an
1954 // interface dependency, or the translation unit containing P imports U, in
1955 // either case prior to P ([module.import]).
1956 //
1957 // [module.import]/p10
1958 // A translation unit has an interface dependency on a translation unit U if
1959 // it contains a declaration (possibly a module-declaration) that imports U
1960 // or if it has an interface dependency on a translation unit that has an
1961 // interface dependency on U.
1962 //
1963 // So we could conclude the module unit U is necessarily reachable if:
1964 // (1) The module unit U is module interface unit.
1965 // (2) The current unit has an interface dependency on the module unit U.
1966 //
1967 // Here we only check for the first condition. Since we couldn't see
1968 // DeclModule if it isn't (transitively) imported.
1969 if (DeclModule->getTopLevelModule()->isModuleInterfaceUnit())
1970 return true;
1971
1972 // [module.reach]/p2
1973 // Additional translation units on
1974 // which the point within the program has an interface dependency may be
1975 // considered reachable, but it is unspecified which are and under what
1976 // circumstances.
1977 //
1978 // The decision here is to treat all additional tranditional units as
1979 // unreachable.
1980 return false;
1981}
1982
1983bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {
1984 return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);
1985}
1986
1987bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1988 // FIXME: If there are both visible and hidden declarations, we need to take
1989 // into account whether redeclaration is possible. Example:
1990 //
1991 // Non-imported module:
1992 // int f(T); // #1
1993 // Some TU:
1994 // static int f(U); // #2, not a redeclaration of #1
1995 // int f(T); // #3, finds both, should link with #1 if T != U, but
1996 // // with #2 if T == U; neither should be ambiguous.
1997 for (auto *D : R) {
1998 if (isVisible(D))
1999 return true;
2000 assert(D->isExternallyDeclarable() &&
2001 "should not have hidden, non-externally-declarable result here");
2002 }
2003
2004 // This function is called once "New" is essentially complete, but before a
2005 // previous declaration is attached. We can't query the linkage of "New" in
2006 // general, because attaching the previous declaration can change the
2007 // linkage of New to match the previous declaration.
2008 //
2009 // However, because we've just determined that there is no *visible* prior
2010 // declaration, we can compute the linkage here. There are two possibilities:
2011 //
2012 // * This is not a redeclaration; it's safe to compute the linkage now.
2013 //
2014 // * This is a redeclaration of a prior declaration that is externally
2015 // redeclarable. In that case, the linkage of the declaration is not
2016 // changed by attaching the prior declaration, because both are externally
2017 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
2018 //
2019 // FIXME: This is subtle and fragile.
2020 return New->isExternallyDeclarable();
2021}
2022
2023/// Retrieve the visible declaration corresponding to D, if any.
2024///
2025/// This routine determines whether the declaration D is visible in the current
2026/// module, with the current imports. If not, it checks whether any
2027/// redeclaration of D is visible, and if so, returns that declaration.
2028///
2029/// \returns D, or a visible previous declaration of D, whichever is more recent
2030/// and visible. If no declaration of D is visible, returns null.
2032 unsigned IDNS) {
2033 assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");
2034
2035 for (auto *RD : D->redecls()) {
2036 // Don't bother with extra checks if we already know this one isn't visible.
2037 if (RD == D)
2038 continue;
2039
2040 auto ND = cast<NamedDecl>(RD);
2041 // FIXME: This is wrong in the case where the previous declaration is not
2042 // visible in the same scope as D. This needs to be done much more
2043 // carefully.
2044 if (ND->isInIdentifierNamespace(IDNS) &&
2046 return ND;
2047 }
2048
2049 return nullptr;
2050}
2051
2054 assert(!isVisible(D) && "not in slow case");
2056 *this, D, Modules, [](const NamedDecl *) { return true; },
2058}
2059
2061 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
2062 assert(!isReachable(D) && "not in slow case");
2064 *this, D, Modules, [](const NamedDecl *) { return true; },
2066}
2067
2068NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
2069 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
2070 // Namespaces are a bit of a special case: we expect there to be a lot of
2071 // redeclarations of some namespaces, all declarations of a namespace are
2072 // essentially interchangeable, all declarations are found by name lookup
2073 // if any is, and namespaces are never looked up during template
2074 // instantiation. So we benefit from caching the check in this case, and
2075 // it is correct to do so.
2076 auto *Key = ND->getCanonicalDecl();
2077 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
2078 return Acceptable;
2079 auto *Acceptable = isVisible(getSema(), Key)
2080 ? Key
2081 : findAcceptableDecl(getSema(), Key, IDNS);
2082 if (Acceptable)
2083 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
2084 return Acceptable;
2085 }
2086
2087 return findAcceptableDecl(getSema(), D, IDNS);
2088}
2089
2091 // If this declaration is already visible, return it directly.
2092 if (D->isUnconditionallyVisible())
2093 return true;
2094
2095 // During template instantiation, we can refer to hidden declarations, if
2096 // they were visible in any module along the path of instantiation.
2097 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);
2098}
2099
2101 if (D->isUnconditionallyVisible())
2102 return true;
2103
2104 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);
2105}
2106
2108 // We should check the visibility at the callsite already.
2109 if (isVisible(SemaRef, ND))
2110 return true;
2111
2112 // Deduction guide lives in namespace scope generally, but it is just a
2113 // hint to the compilers. What we actually lookup for is the generated member
2114 // of the corresponding template. So it is sufficient to check the
2115 // reachability of the template decl.
2116 if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())
2117 return SemaRef.hasReachableDefinition(DeductionGuide);
2118
2119 // FIXME: The lookup for allocation function is a standalone process.
2120 // (We can find the logics in Sema::FindAllocationFunctions)
2121 //
2122 // Such structure makes it a problem when we instantiate a template
2123 // declaration using placement allocation function if the placement
2124 // allocation function is invisible.
2125 // (See https://github.com/llvm/llvm-project/issues/59601)
2126 //
2127 // Here we workaround it by making the placement allocation functions
2128 // always acceptable. The downside is that we can't diagnose the direct
2129 // use of the invisible placement allocation functions. (Although such uses
2130 // should be rare).
2131 if (auto *FD = dyn_cast<FunctionDecl>(ND);
2132 FD && FD->isReservedGlobalPlacementOperator())
2133 return true;
2134
2135 auto *DC = ND->getDeclContext();
2136 // If ND is not visible and it is at namespace scope, it shouldn't be found
2137 // by name lookup.
2138 if (DC->isFileContext())
2139 return false;
2140
2141 // [module.interface]p7
2142 // Class and enumeration member names can be found by name lookup in any
2143 // context in which a definition of the type is reachable.
2144 //
2145 // FIXME: The current implementation didn't consider about scope. For example,
2146 // ```
2147 // // m.cppm
2148 // export module m;
2149 // enum E1 { e1 };
2150 // // Use.cpp
2151 // import m;
2152 // void test() {
2153 // auto a = E1::e1; // Error as expected.
2154 // auto b = e1; // Should be error. namespace-scope name e1 is not visible
2155 // }
2156 // ```
2157 // For the above example, the current implementation would emit error for `a`
2158 // correctly. However, the implementation wouldn't diagnose about `b` now.
2159 // Since we only check the reachability for the parent only.
2160 // See clang/test/CXX/module/module.interface/p7.cpp for example.
2161 if (auto *TD = dyn_cast<TagDecl>(DC))
2162 return SemaRef.hasReachableDefinition(TD);
2163
2164 return false;
2165}
2166
2167/// Perform unqualified name lookup starting from a given
2168/// scope.
2169///
2170/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
2171/// used to find names within the current scope. For example, 'x' in
2172/// @code
2173/// int x;
2174/// int f() {
2175/// return x; // unqualified name look finds 'x' in the global scope
2176/// }
2177/// @endcode
2178///
2179/// Different lookup criteria can find different names. For example, a
2180/// particular scope can have both a struct and a function of the same
2181/// name, and each can be found by certain lookup criteria. For more
2182/// information about lookup criteria, see the documentation for the
2183/// class LookupCriteria.
2184///
2185/// @param S The scope from which unqualified name lookup will
2186/// begin. If the lookup criteria permits, name lookup may also search
2187/// in the parent scopes.
2188///
2189/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
2190/// look up and the lookup kind), and is updated with the results of lookup
2191/// including zero or more declarations and possibly additional information
2192/// used to diagnose ambiguities.
2193///
2194/// @returns \c true if lookup succeeded and false otherwise.
2195bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
2196 bool ForceNoCPlusPlus) {
2197 DeclarationName Name = R.getLookupName();
2198 if (!Name) return false;
2199
2200 LookupNameKind NameKind = R.getLookupKind();
2201
2202 if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
2203 // Unqualified name lookup in C/Objective-C is purely lexical, so
2204 // search in the declarations attached to the name.
2205 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
2206 // Find the nearest non-transparent declaration scope.
2207 while (!(S->getFlags() & Scope::DeclScope) ||
2208 (S->getEntity() && S->getEntity()->isTransparentContext()))
2209 S = S->getParent();
2210 }
2211
2212 // When performing a scope lookup, we want to find local extern decls.
2213 FindLocalExternScope FindLocals(R);
2214
2215 // Scan up the scope chain looking for a decl that matches this
2216 // identifier that is in the appropriate namespace. This search
2217 // should not take long, as shadowing of names is uncommon, and
2218 // deep shadowing is extremely uncommon.
2219 bool LeftStartingScope = false;
2220
2222 IEnd = IdResolver.end();
2223 I != IEnd; ++I)
2224 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
2225 if (NameKind == LookupRedeclarationWithLinkage) {
2226 // Determine whether this (or a previous) declaration is
2227 // out-of-scope.
2228 if (!LeftStartingScope && !S->isDeclScope(*I))
2229 LeftStartingScope = true;
2230
2231 // If we found something outside of our starting scope that
2232 // does not have linkage, skip it.
2233 if (LeftStartingScope && !((*I)->hasLinkage())) {
2234 R.setShadowed();
2235 continue;
2236 }
2237 }
2238 else if (NameKind == LookupObjCImplicitSelfParam &&
2239 !isa<ImplicitParamDecl>(*I))
2240 continue;
2241
2242 R.addDecl(D);
2243
2244 // Check whether there are any other declarations with the same name
2245 // and in the same scope.
2246 if (I != IEnd) {
2247 // Find the scope in which this declaration was declared (if it
2248 // actually exists in a Scope).
2249 while (S && !S->isDeclScope(D))
2250 S = S->getParent();
2251
2252 // If the scope containing the declaration is the translation unit,
2253 // then we'll need to perform our checks based on the matching
2254 // DeclContexts rather than matching scopes.
2256 S = nullptr;
2257
2258 // Compute the DeclContext, if we need it.
2259 DeclContext *DC = nullptr;
2260 if (!S)
2261 DC = (*I)->getDeclContext()->getRedeclContext();
2262
2264 for (++LastI; LastI != IEnd; ++LastI) {
2265 if (S) {
2266 // Match based on scope.
2267 if (!S->isDeclScope(*LastI))
2268 break;
2269 } else {
2270 // Match based on DeclContext.
2271 DeclContext *LastDC
2272 = (*LastI)->getDeclContext()->getRedeclContext();
2273 if (!LastDC->Equals(DC))
2274 break;
2275 }
2276
2277 // If the declaration is in the right namespace and visible, add it.
2278 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
2279 R.addDecl(LastD);
2280 }
2281
2282 R.resolveKind();
2283 }
2284
2285 return true;
2286 }
2287 } else {
2288 // Perform C++ unqualified name lookup.
2289 if (CppLookupName(R, S))
2290 return true;
2291 }
2292
2293 // If we didn't find a use of this identifier, and if the identifier
2294 // corresponds to a compiler builtin, create the decl object for the builtin
2295 // now, injecting it into translation unit scope, and return it.
2296 if (AllowBuiltinCreation && LookupBuiltin(R))
2297 return true;
2298
2299 // If we didn't find a use of this identifier, the ExternalSource
2300 // may be able to handle the situation.
2301 // Note: some lookup failures are expected!
2302 // See e.g. R.isForRedeclaration().
2303 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2304}
2305
2306/// Perform qualified name lookup in the namespaces nominated by
2307/// using directives by the given context.
2308///
2309/// C++98 [namespace.qual]p2:
2310/// Given X::m (where X is a user-declared namespace), or given \::m
2311/// (where X is the global namespace), let S be the set of all
2312/// declarations of m in X and in the transitive closure of all
2313/// namespaces nominated by using-directives in X and its used
2314/// namespaces, except that using-directives are ignored in any
2315/// namespace, including X, directly containing one or more
2316/// declarations of m. No namespace is searched more than once in
2317/// the lookup of a name. If S is the empty set, the program is
2318/// ill-formed. Otherwise, if S has exactly one member, or if the
2319/// context of the reference is a using-declaration
2320/// (namespace.udecl), S is the required set of declarations of
2321/// m. Otherwise if the use of m is not one that allows a unique
2322/// declaration to be chosen from S, the program is ill-formed.
2323///
2324/// C++98 [namespace.qual]p5:
2325/// During the lookup of a qualified namespace member name, if the
2326/// lookup finds more than one declaration of the member, and if one
2327/// declaration introduces a class name or enumeration name and the
2328/// other declarations either introduce the same object, the same
2329/// enumerator or a set of functions, the non-type name hides the
2330/// class or enumeration name if and only if the declarations are
2331/// from the same namespace; otherwise (the declarations are from
2332/// different namespaces), the program is ill-formed.
2334 DeclContext *StartDC) {
2335 assert(StartDC->isFileContext() && "start context is not a file context");
2336
2337 // We have not yet looked into these namespaces, much less added
2338 // their "using-children" to the queue.
2340
2341 // We have at least added all these contexts to the queue.
2343 Visited.insert(StartDC);
2344
2345 // We have already looked into the initial namespace; seed the queue
2346 // with its using-children.
2347 for (auto *I : StartDC->using_directives()) {
2348 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
2349 if (S.isVisible(I) && Visited.insert(ND).second)
2350 Queue.push_back(ND);
2351 }
2352
2353 // The easiest way to implement the restriction in [namespace.qual]p5
2354 // is to check whether any of the individual results found a tag
2355 // and, if so, to declare an ambiguity if the final result is not
2356 // a tag.
2357 bool FoundTag = false;
2358 bool FoundNonTag = false;
2359
2361
2362 bool Found = false;
2363 while (!Queue.empty()) {
2364 NamespaceDecl *ND = Queue.pop_back_val();
2365
2366 // We go through some convolutions here to avoid copying results
2367 // between LookupResults.
2368 bool UseLocal = !R.empty();
2369 LookupResult &DirectR = UseLocal ? LocalR : R;
2370 bool FoundDirect = LookupDirect(S, DirectR, ND);
2371
2372 if (FoundDirect) {
2373 // First do any local hiding.
2374 DirectR.resolveKind();
2375
2376 // If the local result is a tag, remember that.
2377 if (DirectR.isSingleTagDecl())
2378 FoundTag = true;
2379 else
2380 FoundNonTag = true;
2381
2382 // Append the local results to the total results if necessary.
2383 if (UseLocal) {
2384 R.addAllDecls(LocalR);
2385 LocalR.clear();
2386 }
2387 }
2388
2389 // If we find names in this namespace, ignore its using directives.
2390 if (FoundDirect) {
2391 Found = true;
2392 continue;
2393 }
2394
2395 for (auto *I : ND->using_directives()) {
2396 NamespaceDecl *Nom = I->getNominatedNamespace();
2397 if (S.isVisible(I) && Visited.insert(Nom).second)
2398 Queue.push_back(Nom);
2399 }
2400 }
2401
2402 if (Found) {
2403 if (FoundTag && FoundNonTag)
2405 else
2406 R.resolveKind();
2407 }
2408
2409 return Found;
2410}
2411
2412/// Perform qualified name lookup into a given context.
2413///
2414/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2415/// names when the context of those names is explicit specified, e.g.,
2416/// "std::vector" or "x->member", or as part of unqualified name lookup.
2417///
2418/// Different lookup criteria can find different names. For example, a
2419/// particular scope can have both a struct and a function of the same
2420/// name, and each can be found by certain lookup criteria. For more
2421/// information about lookup criteria, see the documentation for the
2422/// class LookupCriteria.
2423///
2424/// \param R captures both the lookup criteria and any lookup results found.
2425///
2426/// \param LookupCtx The context in which qualified name lookup will
2427/// search. If the lookup criteria permits, name lookup may also search
2428/// in the parent contexts or (for C++ classes) base classes.
2429///
2430/// \param InUnqualifiedLookup true if this is qualified name lookup that
2431/// occurs as part of unqualified name lookup.
2432///
2433/// \returns true if lookup succeeded, false if it failed.
2435 bool InUnqualifiedLookup) {
2436 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2437
2438 if (!R.getLookupName())
2439 return false;
2440
2441 // Make sure that the declaration context is complete.
2442 assert((!isa<TagDecl>(LookupCtx) ||
2443 LookupCtx->isDependentContext() ||
2444 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2445 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2446 "Declaration context must already be complete!");
2447
2448 struct QualifiedLookupInScope {
2449 bool oldVal;
2450 DeclContext *Context;
2451 // Set flag in DeclContext informing debugger that we're looking for qualified name
2452 QualifiedLookupInScope(DeclContext *ctx)
2453 : oldVal(ctx->shouldUseQualifiedLookup()), Context(ctx) {
2454 ctx->setUseQualifiedLookup();
2455 }
2456 ~QualifiedLookupInScope() {
2457 Context->setUseQualifiedLookup(oldVal);
2458 }
2459 } QL(LookupCtx);
2460
2461 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2462 // FIXME: Per [temp.dep.general]p2, an unqualified name is also dependent
2463 // if it's a dependent conversion-function-id or operator= where the current
2464 // class is a templated entity. This should be handled in LookupName.
2465 if (!InUnqualifiedLookup && !R.isForRedeclaration()) {
2466 // C++23 [temp.dep.type]p5:
2467 // A qualified name is dependent if
2468 // - it is a conversion-function-id whose conversion-type-id
2469 // is dependent, or
2470 // - [...]
2471 // - its lookup context is the current instantiation and it
2472 // is operator=, or
2473 // - [...]
2474 if (DeclarationName Name = R.getLookupName();
2475 Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2476 Name.getCXXNameType()->isDependentType()) {
2478 return false;
2479 }
2480 }
2481
2482 if (LookupDirect(*this, R, LookupCtx)) {
2483 R.resolveKind();
2484 if (LookupRec)
2485 R.setNamingClass(LookupRec);
2486 return true;
2487 }
2488
2489 // Don't descend into implied contexts for redeclarations.
2490 // C++98 [namespace.qual]p6:
2491 // In a declaration for a namespace member in which the
2492 // declarator-id is a qualified-id, given that the qualified-id
2493 // for the namespace member has the form
2494 // nested-name-specifier unqualified-id
2495 // the unqualified-id shall name a member of the namespace
2496 // designated by the nested-name-specifier.
2497 // See also [class.mfct]p5 and [class.static.data]p2.
2498 if (R.isForRedeclaration())
2499 return false;
2500
2501 // If this is a namespace, look it up in the implied namespaces.
2502 if (LookupCtx->isFileContext())
2503 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2504
2505 // If this isn't a C++ class, we aren't allowed to look into base
2506 // classes, we're done.
2507 if (!LookupRec || !LookupRec->getDefinition())
2508 return false;
2509
2510 // We're done for lookups that can never succeed for C++ classes.
2511 if (R.getLookupKind() == LookupOperatorName ||
2515 return false;
2516
2517 // If we're performing qualified name lookup into a dependent class,
2518 // then we are actually looking into a current instantiation. If we have any
2519 // dependent base classes, then we either have to delay lookup until
2520 // template instantiation time (at which point all bases will be available)
2521 // or we have to fail.
2522 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2523 LookupRec->hasAnyDependentBases()) {
2525 return false;
2526 }
2527
2528 // Perform lookup into our base classes.
2529
2530 DeclarationName Name = R.getLookupName();
2531 unsigned IDNS = R.getIdentifierNamespace();
2532
2533 // Look for this member in our base classes.
2534 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2535 CXXBasePath &Path) -> bool {
2536 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2537 // Drop leading non-matching lookup results from the declaration list so
2538 // we don't need to consider them again below.
2539 for (Path.Decls = BaseRecord->lookup(Name).begin();
2540 Path.Decls != Path.Decls.end(); ++Path.Decls) {
2541 if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2542 return true;
2543 }
2544 return false;
2545 };
2546
2547 CXXBasePaths Paths;
2548 Paths.setOrigin(LookupRec);
2549 if (!LookupRec->lookupInBases(BaseCallback, Paths))
2550 return false;
2551
2552 R.setNamingClass(LookupRec);
2553
2554 // C++ [class.member.lookup]p2:
2555 // [...] If the resulting set of declarations are not all from
2556 // sub-objects of the same type, or the set has a nonstatic member
2557 // and includes members from distinct sub-objects, there is an
2558 // ambiguity and the program is ill-formed. Otherwise that set is
2559 // the result of the lookup.
2560 QualType SubobjectType;
2561 int SubobjectNumber = 0;
2562 AccessSpecifier SubobjectAccess = AS_none;
2563
2564 // Check whether the given lookup result contains only static members.
2565 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2566 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2567 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2568 return false;
2569 return true;
2570 };
2571
2572 bool TemplateNameLookup = R.isTemplateNameLookup();
2573
2574 // Determine whether two sets of members contain the same members, as
2575 // required by C++ [class.member.lookup]p6.
2576 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2578 using Iterator = DeclContextLookupResult::iterator;
2579 using Result = const void *;
2580
2581 auto Next = [&](Iterator &It, Iterator End) -> Result {
2582 while (It != End) {
2583 NamedDecl *ND = *It++;
2584 if (!ND->isInIdentifierNamespace(IDNS))
2585 continue;
2586
2587 // C++ [temp.local]p3:
2588 // A lookup that finds an injected-class-name (10.2) can result in
2589 // an ambiguity in certain cases (for example, if it is found in
2590 // more than one base class). If all of the injected-class-names
2591 // that are found refer to specializations of the same class
2592 // template, and if the name is used as a template-name, the
2593 // reference refers to the class template itself and not a
2594 // specialization thereof, and is not ambiguous.
2595 if (TemplateNameLookup)
2596 if (auto *TD = getAsTemplateNameDecl(ND))
2597 ND = TD;
2598
2599 // C++ [class.member.lookup]p3:
2600 // type declarations (including injected-class-names) are replaced by
2601 // the types they designate
2602 if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {
2604 return T.getCanonicalType().getAsOpaquePtr();
2605 }
2606
2607 return ND->getUnderlyingDecl()->getCanonicalDecl();
2608 }
2609 return nullptr;
2610 };
2611
2612 // We'll often find the declarations are in the same order. Handle this
2613 // case (and the special case of only one declaration) efficiently.
2614 Iterator AIt = A, BIt = B, AEnd, BEnd;
2615 while (true) {
2616 Result AResult = Next(AIt, AEnd);
2617 Result BResult = Next(BIt, BEnd);
2618 if (!AResult && !BResult)
2619 return true;
2620 if (!AResult || !BResult)
2621 return false;
2622 if (AResult != BResult) {
2623 // Found a mismatch; carefully check both lists, accounting for the
2624 // possibility of declarations appearing more than once.
2625 llvm::SmallDenseMap<Result, bool, 32> AResults;
2626 for (; AResult; AResult = Next(AIt, AEnd))
2627 AResults.insert({AResult, /*FoundInB*/false});
2628 unsigned Found = 0;
2629 for (; BResult; BResult = Next(BIt, BEnd)) {
2630 auto It = AResults.find(BResult);
2631 if (It == AResults.end())
2632 return false;
2633 if (!It->second) {
2634 It->second = true;
2635 ++Found;
2636 }
2637 }
2638 return AResults.size() == Found;
2639 }
2640 }
2641 };
2642
2643 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2644 Path != PathEnd; ++Path) {
2645 const CXXBasePathElement &PathElement = Path->back();
2646
2647 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2648 // across all paths.
2649 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2650
2651 // Determine whether we're looking at a distinct sub-object or not.
2652 if (SubobjectType.isNull()) {
2653 // This is the first subobject we've looked at. Record its type.
2654 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2655 SubobjectNumber = PathElement.SubobjectNumber;
2656 continue;
2657 }
2658
2659 if (SubobjectType !=
2660 Context.getCanonicalType(PathElement.Base->getType())) {
2661 // We found members of the given name in two subobjects of
2662 // different types. If the declaration sets aren't the same, this
2663 // lookup is ambiguous.
2664 //
2665 // FIXME: The language rule says that this applies irrespective of
2666 // whether the sets contain only static members.
2667 if (HasOnlyStaticMembers(Path->Decls) &&
2668 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2669 continue;
2670
2671 R.setAmbiguousBaseSubobjectTypes(Paths);
2672 return true;
2673 }
2674
2675 // FIXME: This language rule no longer exists. Checking for ambiguous base
2676 // subobjects should be done as part of formation of a class member access
2677 // expression (when converting the object parameter to the member's type).
2678 if (SubobjectNumber != PathElement.SubobjectNumber) {
2679 // We have a different subobject of the same type.
2680
2681 // C++ [class.member.lookup]p5:
2682 // A static member, a nested type or an enumerator defined in
2683 // a base class T can unambiguously be found even if an object
2684 // has more than one base class subobject of type T.
2685 if (HasOnlyStaticMembers(Path->Decls))
2686 continue;
2687
2688 // We have found a nonstatic member name in multiple, distinct
2689 // subobjects. Name lookup is ambiguous.
2690 R.setAmbiguousBaseSubobjects(Paths);
2691 return true;
2692 }
2693 }
2694
2695 // Lookup in a base class succeeded; return these results.
2696
2697 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2698 I != E; ++I) {
2699 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2700 (*I)->getAccess());
2701 if (NamedDecl *ND = R.getAcceptableDecl(*I))
2702 R.addDecl(ND, AS);
2703 }
2704 R.resolveKind();
2705 return true;
2706}
2707
2708/// Performs qualified name lookup or special type of lookup for
2709/// "__super::" scope specifier.
2710///
2711/// This routine is a convenience overload meant to be called from contexts
2712/// that need to perform a qualified name lookup with an optional C++ scope
2713/// specifier that might require special kind of lookup.
2714///
2715/// \param R captures both the lookup criteria and any lookup results found.
2716///
2717/// \param LookupCtx The context in which qualified name lookup will
2718/// search.
2719///
2720/// \param SS An optional C++ scope-specifier.
2721///
2722/// \returns true if lookup succeeded, false if it failed.
2724 CXXScopeSpec &SS) {
2725 auto *NNS = SS.getScopeRep();
2726 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2727 return LookupInSuper(R, NNS->getAsRecordDecl());
2728 else
2729
2730 return LookupQualifiedName(R, LookupCtx);
2731}
2732
2733/// Performs name lookup for a name that was parsed in the
2734/// source code, and may contain a C++ scope specifier.
2735///
2736/// This routine is a convenience routine meant to be called from
2737/// contexts that receive a name and an optional C++ scope specifier
2738/// (e.g., "N::M::x"). It will then perform either qualified or
2739/// unqualified name lookup (with LookupQualifiedName or LookupName,
2740/// respectively) on the given name and return those results. It will
2741/// perform a special type of lookup for "__super::" scope specifier.
2742///
2743/// @param S The scope from which unqualified name lookup will
2744/// begin.
2745///
2746/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
2747///
2748/// @param EnteringContext Indicates whether we are going to enter the
2749/// context of the scope-specifier SS (if present).
2750///
2751/// @returns True if any decls were found (but possibly ambiguous)
2753 QualType ObjectType, bool AllowBuiltinCreation,
2754 bool EnteringContext) {
2755 // When the scope specifier is invalid, don't even look for anything.
2756 if (SS && SS->isInvalid())
2757 return false;
2758
2759 // Determine where to perform name lookup
2760 DeclContext *DC = nullptr;
2761 bool IsDependent = false;
2762 if (!ObjectType.isNull()) {
2763 // This nested-name-specifier occurs in a member access expression, e.g.,
2764 // x->B::f, and we are looking into the type of the object.
2765 assert((!SS || SS->isEmpty()) &&
2766 "ObjectType and scope specifier cannot coexist");
2767 DC = computeDeclContext(ObjectType);
2768 IsDependent = !DC && ObjectType->isDependentType();
2769 assert(((!DC && ObjectType->isDependentType()) ||
2770 !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() ||
2771 ObjectType->castAs<TagType>()->isBeingDefined()) &&
2772 "Caller should have completed object type");
2773 } else if (SS && SS->isNotEmpty()) {
2774 if (NestedNameSpecifier *NNS = SS->getScopeRep();
2776 return LookupInSuper(R, NNS->getAsRecordDecl());
2777 // This nested-name-specifier occurs after another nested-name-specifier,
2778 // so long into the context associated with the prior nested-name-specifier.
2779 if ((DC = computeDeclContext(*SS, EnteringContext))) {
2780 // The declaration context must be complete.
2781 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2782 return false;
2783 R.setContextRange(SS->getRange());
2784 }
2785 IsDependent = !DC && isDependentScopeSpecifier(*SS);
2786 } else {
2787 // Perform unqualified name lookup starting in the given scope.
2788 return LookupName(R, S, AllowBuiltinCreation);
2789 }
2790
2791 // If we were able to compute a declaration context, perform qualified name
2792 // lookup in that context.
2793 if (DC)
2794 return LookupQualifiedName(R, DC);
2795 else if (IsDependent)
2796 // We could not resolve the scope specified to a specific declaration
2797 // context, which means that SS refers to an unknown specialization.
2798 // Name lookup can't find anything in this case.
2800 return false;
2801}
2802
2803/// Perform qualified name lookup into all base classes of the given
2804/// class.
2805///
2806/// \param R captures both the lookup criteria and any lookup results found.
2807///
2808/// \param Class The context in which qualified name lookup will
2809/// search. Name lookup will search in all base classes merging the results.
2810///
2811/// @returns True if any decls were found (but possibly ambiguous)
2813 // The access-control rules we use here are essentially the rules for
2814 // doing a lookup in Class that just magically skipped the direct
2815 // members of Class itself. That is, the naming class is Class, and the
2816 // access includes the access of the base.
2817 for (const auto &BaseSpec : Class->bases()) {
2818 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2819 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2821 Result.setBaseObjectType(Context.getRecordType(Class));
2823
2824 // Copy the lookup results into the target, merging the base's access into
2825 // the path access.
2826 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2827 R.addDecl(I.getDecl(),
2828 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2829 I.getAccess()));
2830 }
2831
2832 Result.suppressDiagnostics();
2833 }
2834
2835 R.resolveKind();
2837
2838 return !R.empty();
2839}
2840
2841/// Produce a diagnostic describing the ambiguity that resulted
2842/// from name lookup.
2843///
2844/// \param Result The result of the ambiguous lookup to be diagnosed.
2846 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2847
2848 DeclarationName Name = Result.getLookupName();
2849 SourceLocation NameLoc = Result.getNameLoc();
2850 SourceRange LookupRange = Result.getContextRange();
2851
2852 switch (Result.getAmbiguityKind()) {
2854 CXXBasePaths *Paths = Result.getBasePaths();
2855 QualType SubobjectType = Paths->front().back().Base->getType();
2856 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2857 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2858 << LookupRange;
2859
2860 DeclContext::lookup_iterator Found = Paths->front().Decls;
2861 while (isa<CXXMethodDecl>(*Found) &&
2862 cast<CXXMethodDecl>(*Found)->isStatic())
2863 ++Found;
2864
2865 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2866 break;
2867 }
2868
2870 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2871 << Name << LookupRange;
2872
2873 CXXBasePaths *Paths = Result.getBasePaths();
2874 std::set<const NamedDecl *> DeclsPrinted;
2875 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2876 PathEnd = Paths->end();
2877 Path != PathEnd; ++Path) {
2878 const NamedDecl *D = *Path->Decls;
2879 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2880 continue;
2881 if (DeclsPrinted.insert(D).second) {
2882 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2883 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2884 << TD->getUnderlyingType();
2885 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2886 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2887 << Context.getTypeDeclType(TD);
2888 else
2889 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2890 }
2891 }
2892 break;
2893 }
2894
2896 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2897
2899
2900 for (auto *D : Result)
2901 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2902 TagDecls.insert(TD);
2903 Diag(TD->getLocation(), diag::note_hidden_tag);
2904 }
2905
2906 for (auto *D : Result)
2907 if (!isa<TagDecl>(D))
2908 Diag(D->getLocation(), diag::note_hiding_object);
2909
2910 // For recovery purposes, go ahead and implement the hiding.
2911 LookupResult::Filter F = Result.makeFilter();
2912 while (F.hasNext()) {
2913 if (TagDecls.count(F.next()))
2914 F.erase();
2915 }
2916 F.done();
2917 break;
2918 }
2919
2921 Diag(NameLoc, diag::err_using_placeholder_variable) << Name << LookupRange;
2922 DeclContext *DC = nullptr;
2923 for (auto *D : Result) {
2924 Diag(D->getLocation(), diag::note_reference_placeholder) << D;
2925 if (DC != nullptr && DC != D->getDeclContext())
2926 break;
2927 DC = D->getDeclContext();
2928 }
2929 break;
2930 }
2931
2933 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2934
2935 for (auto *D : Result)
2936 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2937 break;
2938 }
2939 }
2940}
2941
2942namespace {
2943 struct AssociatedLookup {
2944 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2945 Sema::AssociatedNamespaceSet &Namespaces,
2946 Sema::AssociatedClassSet &Classes)
2947 : S(S), Namespaces(Namespaces), Classes(Classes),
2948 InstantiationLoc(InstantiationLoc) {
2949 }
2950
2951 bool addClassTransitive(CXXRecordDecl *RD) {
2952 Classes.insert(RD);
2953 return ClassesTransitive.insert(RD);
2954 }
2955
2956 Sema &S;
2957 Sema::AssociatedNamespaceSet &Namespaces;
2958 Sema::AssociatedClassSet &Classes;
2959 SourceLocation InstantiationLoc;
2960
2961 private:
2962 Sema::AssociatedClassSet ClassesTransitive;
2963 };
2964} // end anonymous namespace
2965
2966static void
2968
2969// Given the declaration context \param Ctx of a class, class template or
2970// enumeration, add the associated namespaces to \param Namespaces as described
2971// in [basic.lookup.argdep]p2.
2973 DeclContext *Ctx) {
2974 // The exact wording has been changed in C++14 as a result of
2975 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2976 // to all language versions since it is possible to return a local type
2977 // from a lambda in C++11.
2978 //
2979 // C++14 [basic.lookup.argdep]p2:
2980 // If T is a class type [...]. Its associated namespaces are the innermost
2981 // enclosing namespaces of its associated classes. [...]
2982 //
2983 // If T is an enumeration type, its associated namespace is the innermost
2984 // enclosing namespace of its declaration. [...]
2985
2986 // We additionally skip inline namespaces. The innermost non-inline namespace
2987 // contains all names of all its nested inline namespaces anyway, so we can
2988 // replace the entire inline namespace tree with its root.
2989 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2990 Ctx = Ctx->getParent();
2991
2992 Namespaces.insert(Ctx->getPrimaryContext());
2993}
2994
2995// Add the associated classes and namespaces for argument-dependent
2996// lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2997static void
2999 const TemplateArgument &Arg) {
3000 // C++ [basic.lookup.argdep]p2, last bullet:
3001 // -- [...] ;
3002 switch (Arg.getKind()) {
3004 break;
3005
3007 // [...] the namespaces and classes associated with the types of the
3008 // template arguments provided for template type parameters (excluding
3009 // template template parameters)
3011 break;
3012
3015 // [...] the namespaces in which any template template arguments are
3016 // defined; and the classes in which any member templates used as
3017 // template template arguments are defined.
3019 if (ClassTemplateDecl *ClassTemplate
3020 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
3021 DeclContext *Ctx = ClassTemplate->getDeclContext();
3022 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3023 Result.Classes.insert(EnclosingClass);
3024 // Add the associated namespace for this class.
3025 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3026 }
3027 break;
3028 }
3029
3035 // [Note: non-type template arguments do not contribute to the set of
3036 // associated namespaces. ]
3037 break;
3038
3040 for (const auto &P : Arg.pack_elements())
3042 break;
3043 }
3044}
3045
3046// Add the associated classes and namespaces for argument-dependent lookup
3047// with an argument of class type (C++ [basic.lookup.argdep]p2).
3048static void
3051
3052 // Just silently ignore anything whose name is __va_list_tag.
3053 if (Class->getDeclName() == Result.S.VAListTagName)
3054 return;
3055
3056 // C++ [basic.lookup.argdep]p2:
3057 // [...]
3058 // -- If T is a class type (including unions), its associated
3059 // classes are: the class itself; the class of which it is a
3060 // member, if any; and its direct and indirect base classes.
3061 // Its associated namespaces are the innermost enclosing
3062 // namespaces of its associated classes.
3063
3064 // Add the class of which it is a member, if any.
3065 DeclContext *Ctx = Class->getDeclContext();
3066 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3067 Result.Classes.insert(EnclosingClass);
3068
3069 // Add the associated namespace for this class.
3070 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3071
3072 // -- If T is a template-id, its associated namespaces and classes are
3073 // the namespace in which the template is defined; for member
3074 // templates, the member template's class; the namespaces and classes
3075 // associated with the types of the template arguments provided for
3076 // template type parameters (excluding template template parameters); the
3077 // namespaces in which any template template arguments are defined; and
3078 // the classes in which any member templates used as template template
3079 // arguments are defined. [Note: non-type template arguments do not
3080 // contribute to the set of associated namespaces. ]
3082 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
3083 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
3084 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3085 Result.Classes.insert(EnclosingClass);
3086 // Add the associated namespace for this class.
3087 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3088
3089 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3090 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3091 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
3092 }
3093
3094 // Add the class itself. If we've already transitively visited this class,
3095 // we don't need to visit base classes.
3096 if (!Result.addClassTransitive(Class))
3097 return;
3098
3099 // Only recurse into base classes for complete types.
3100 if (!Result.S.isCompleteType(Result.InstantiationLoc,
3101 Result.S.Context.getRecordType(Class)))
3102 return;
3103
3104 // Add direct and indirect base classes along with their associated
3105 // namespaces.
3107 Bases.push_back(Class);
3108 while (!Bases.empty()) {
3109 // Pop this class off the stack.
3110 Class = Bases.pop_back_val();
3111
3112 // Visit the base classes.
3113 for (const auto &Base : Class->bases()) {
3114 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
3115 // In dependent contexts, we do ADL twice, and the first time around,
3116 // the base type might be a dependent TemplateSpecializationType, or a
3117 // TemplateTypeParmType. If that happens, simply ignore it.
3118 // FIXME: If we want to support export, we probably need to add the
3119 // namespace of the template in a TemplateSpecializationType, or even
3120 // the classes and namespaces of known non-dependent arguments.
3121 if (!BaseType)
3122 continue;
3123 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3124 if (Result.addClassTransitive(BaseDecl)) {
3125 // Find the associated namespace for this base class.
3126 DeclContext *BaseCtx = BaseDecl->getDeclContext();
3127 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
3128
3129 // Make sure we visit the bases of this base class.
3130 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
3131 Bases.push_back(BaseDecl);
3132 }
3133 }
3134 }
3135}
3136
3137// Add the associated classes and namespaces for
3138// argument-dependent lookup with an argument of type T
3139// (C++ [basic.lookup.koenig]p2).
3140static void
3142 // C++ [basic.lookup.koenig]p2:
3143 //
3144 // For each argument type T in the function call, there is a set
3145 // of zero or more associated namespaces and a set of zero or more
3146 // associated classes to be considered. The sets of namespaces and
3147 // classes is determined entirely by the types of the function
3148 // arguments (and the namespace of any template template
3149 // argument). Typedef names and using-declarations used to specify
3150 // the types do not contribute to this set. The sets of namespaces
3151 // and classes are determined in the following way:
3152
3154 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
3155
3156 while (true) {
3157 switch (T->getTypeClass()) {
3158
3159#define TYPE(Class, Base)
3160#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3161#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3162#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3163#define ABSTRACT_TYPE(Class, Base)
3164#include "clang/AST/TypeNodes.inc"
3165 // T is canonical. We can also ignore dependent types because
3166 // we don't need to do ADL at the definition point, but if we
3167 // wanted to implement template export (or if we find some other
3168 // use for associated classes and namespaces...) this would be
3169 // wrong.
3170 break;
3171
3172 // -- If T is a pointer to U or an array of U, its associated
3173 // namespaces and classes are those associated with U.
3174 case Type::Pointer:
3175 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
3176 continue;
3177 case Type::ConstantArray:
3178 case Type::IncompleteArray:
3179 case Type::VariableArray:
3180 T = cast<ArrayType>(T)->getElementType().getTypePtr();
3181 continue;
3182
3183 // -- If T is a fundamental type, its associated sets of
3184 // namespaces and classes are both empty.
3185 case Type::Builtin:
3186 break;
3187
3188 // -- If T is a class type (including unions), its associated
3189 // classes are: the class itself; the class of which it is
3190 // a member, if any; and its direct and indirect base classes.
3191 // Its associated namespaces are the innermost enclosing
3192 // namespaces of its associated classes.
3193 case Type::Record: {
3195 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
3197 break;
3198 }
3199
3200 // -- If T is an enumeration type, its associated namespace
3201 // is the innermost enclosing namespace of its declaration.
3202 // If it is a class member, its associated class is the
3203 // member’s class; else it has no associated class.
3204 case Type::Enum: {
3205 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
3206
3207 DeclContext *Ctx = Enum->getDeclContext();
3208 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3209 Result.Classes.insert(EnclosingClass);
3210
3211 // Add the associated namespace for this enumeration.
3212 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3213
3214 break;
3215 }
3216
3217 // -- If T is a function type, its associated namespaces and
3218 // classes are those associated with the function parameter
3219 // types and those associated with the return type.
3220 case Type::FunctionProto: {
3221 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
3222 for (const auto &Arg : Proto->param_types())
3223 Queue.push_back(Arg.getTypePtr());
3224 // fallthrough
3225 [[fallthrough]];
3226 }
3227 case Type::FunctionNoProto: {
3228 const FunctionType *FnType = cast<FunctionType>(T);
3229 T = FnType->getReturnType().getTypePtr();
3230 continue;
3231 }
3232
3233 // -- If T is a pointer to a member function of a class X, its
3234 // associated namespaces and classes are those associated
3235 // with the function parameter types and return type,
3236 // together with those associated with X.
3237 //
3238 // -- If T is a pointer to a data member of class X, its
3239 // associated namespaces and classes are those associated
3240 // with the member type together with those associated with
3241 // X.
3242 case Type::MemberPointer: {
3243 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
3244
3245 // Queue up the class type into which this points.
3246 Queue.push_back(MemberPtr->getClass());
3247
3248 // And directly continue with the pointee type.
3249 T = MemberPtr->getPointeeType().getTypePtr();
3250 continue;
3251 }
3252
3253 // As an extension, treat this like a normal pointer.
3254 case Type::BlockPointer:
3255 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
3256 continue;
3257
3258 // References aren't covered by the standard, but that's such an
3259 // obvious defect that we cover them anyway.
3260 case Type::LValueReference:
3261 case Type::RValueReference:
3262 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
3263 continue;
3264
3265 // These are fundamental types.
3266 case Type::Vector:
3267 case Type::ExtVector:
3268 case Type::ConstantMatrix:
3269 case Type::Complex:
3270 case Type::BitInt:
3271 break;
3272
3273 // Non-deduced auto types only get here for error cases.
3274 case Type::Auto:
3275 case Type::DeducedTemplateSpecialization:
3276 break;
3277
3278 // If T is an Objective-C object or interface type, or a pointer to an
3279 // object or interface type, the associated namespace is the global
3280 // namespace.
3281 case Type::ObjCObject:
3282 case Type::ObjCInterface:
3283 case Type::ObjCObjectPointer:
3284 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
3285 break;
3286
3287 // Atomic types are just wrappers; use the associations of the
3288 // contained type.
3289 case Type::Atomic:
3290 T = cast<AtomicType>(T)->getValueType().getTypePtr();
3291 continue;
3292 case Type::Pipe:
3293 T = cast<PipeType>(T)->getElementType().getTypePtr();
3294 continue;
3295
3296 // Array parameter types are treated as fundamental types.
3297 case Type::ArrayParameter:
3298 break;
3299 }
3300
3301 if (Queue.empty())
3302 break;
3303 T = Queue.pop_back_val();
3304 }
3305}
3306
3307/// Find the associated classes and namespaces for
3308/// argument-dependent lookup for a call with the given set of
3309/// arguments.
3310///
3311/// This routine computes the sets of associated classes and associated
3312/// namespaces searched by argument-dependent lookup
3313/// (C++ [basic.lookup.argdep]) for a given set of arguments.
3315 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
3316 AssociatedNamespaceSet &AssociatedNamespaces,
3317 AssociatedClassSet &AssociatedClasses) {
3318 AssociatedNamespaces.clear();
3319 AssociatedClasses.clear();
3320
3321 AssociatedLookup Result(*this, InstantiationLoc,
3322 AssociatedNamespaces, AssociatedClasses);
3323
3324 // C++ [basic.lookup.koenig]p2:
3325 // For each argument type T in the function call, there is a set
3326 // of zero or more associated namespaces and a set of zero or more
3327 // associated classes to be considered. The sets of namespaces and
3328 // classes is determined entirely by the types of the function
3329 // arguments (and the namespace of any template template
3330 // argument).
3331 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3332 Expr *Arg = Args[ArgIdx];
3333
3334 if (Arg->getType() != Context.OverloadTy) {
3336 continue;
3337 }
3338
3339 // [...] In addition, if the argument is the name or address of a
3340 // set of overloaded functions and/or function templates, its
3341 // associated classes and namespaces are the union of those
3342 // associated with each of the members of the set: the namespace
3343 // in which the function or function template is defined and the
3344 // classes and namespaces associated with its (non-dependent)
3345 // parameter types and return type.
3347
3348 for (const NamedDecl *D : OE->decls()) {
3349 // Look through any using declarations to find the underlying function.
3350 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
3351
3352 // Add the classes and namespaces associated with the parameter
3353 // types and return type of this function.
3355 }
3356 }
3357}
3358
3361 LookupNameKind NameKind,
3362 RedeclarationKind Redecl) {
3363 LookupResult R(*this, Name, Loc, NameKind, Redecl);
3364 LookupName(R, S);
3365 return R.getAsSingle<NamedDecl>();
3366}
3367
3369 UnresolvedSetImpl &Functions) {
3370 // C++ [over.match.oper]p3:
3371 // -- The set of non-member candidates is the result of the
3372 // unqualified lookup of operator@ in the context of the
3373 // expression according to the usual rules for name lookup in
3374 // unqualified function calls (3.4.2) except that all member
3375 // functions are ignored.
3377 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3378 LookupName(Operators, S);
3379
3380 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3381 Functions.append(Operators.begin(), Operators.end());
3382}
3383
3386 bool ConstArg, bool VolatileArg, bool RValueThis,
3387 bool ConstThis, bool VolatileThis) {
3389 "doing special member lookup into record that isn't fully complete");
3390 RD = RD->getDefinition();
3391 if (RValueThis || ConstThis || VolatileThis)
3394 "constructors and destructors always have unqualified lvalue this");
3395 if (ConstArg || VolatileArg)
3398 "parameter-less special members can't have qualified arguments");
3399
3400 // FIXME: Get the caller to pass in a location for the lookup.
3401 SourceLocation LookupLoc = RD->getLocation();
3402
3403 llvm::FoldingSetNodeID ID;
3404 ID.AddPointer(RD);
3405 ID.AddInteger(llvm::to_underlying(SM));
3406 ID.AddInteger(ConstArg);
3407 ID.AddInteger(VolatileArg);
3408 ID.AddInteger(RValueThis);
3409 ID.AddInteger(ConstThis);
3410 ID.AddInteger(VolatileThis);
3411
3412 void *InsertPoint;
3414 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3415
3416 // This was already cached
3417 if (Result)
3418 return *Result;
3419
3422 SpecialMemberCache.InsertNode(Result, InsertPoint);
3423
3425 if (RD->needsImplicitDestructor()) {
3427 DeclareImplicitDestructor(RD);
3428 });
3429 }
3430 CXXDestructorDecl *DD = RD->getDestructor();
3431 Result->setMethod(DD);
3432 Result->setKind(DD && !DD->isDeleted()
3435 return *Result;
3436 }
3437
3438 // Prepare for overload resolution. Here we construct a synthetic argument
3439 // if necessary and make sure that implicit functions are declared.
3441 DeclarationName Name;
3442 Expr *Arg = nullptr;
3443 unsigned NumArgs;
3444
3445 QualType ArgType = CanTy;
3447
3450 NumArgs = 0;
3453 DeclareImplicitDefaultConstructor(RD);
3454 });
3455 }
3456 } else {
3460 if (RD->needsImplicitCopyConstructor()) {
3462 DeclareImplicitCopyConstructor(RD);
3463 });
3464 }
3467 DeclareImplicitMoveConstructor(RD);
3468 });
3469 }
3470 } else {
3472 if (RD->needsImplicitCopyAssignment()) {
3474 DeclareImplicitCopyAssignment(RD);
3475 });
3476 }
3479 DeclareImplicitMoveAssignment(RD);
3480 });
3481 }
3482 }
3483
3484 if (ConstArg)
3485 ArgType.addConst();
3486 if (VolatileArg)
3487 ArgType.addVolatile();
3488
3489 // This isn't /really/ specified by the standard, but it's implied
3490 // we should be working from a PRValue in the case of move to ensure
3491 // that we prefer to bind to rvalue references, and an LValue in the
3492 // case of copy to ensure we don't bind to rvalue references.
3493 // Possibly an XValue is actually correct in the case of move, but
3494 // there is no semantic difference for class types in this restricted
3495 // case.
3498 VK = VK_LValue;
3499 else
3500 VK = VK_PRValue;
3501 }
3502
3503 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3504
3506 NumArgs = 1;
3507 Arg = &FakeArg;
3508 }
3509
3510 // Create the object argument
3511 QualType ThisTy = CanTy;
3512 if (ConstThis)
3513 ThisTy.addConst();
3514 if (VolatileThis)
3515 ThisTy.addVolatile();
3516 Expr::Classification Classification =
3517 OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
3518 .Classify(Context);
3519
3520 // Now we perform lookup on the name we computed earlier and do overload
3521 // resolution. Lookup is only performed directly into the class since there
3522 // will always be a (possibly implicit) declaration to shadow any others.
3524 DeclContext::lookup_result R = RD->lookup(Name);
3525
3526 if (R.empty()) {
3527 // We might have no default constructor because we have a lambda's closure
3528 // type, rather than because there's some other declared constructor.
3529 // Every class has a copy/move constructor, copy/move assignment, and
3530 // destructor.
3532 "lookup for a constructor or assignment operator was empty");
3533 Result->setMethod(nullptr);
3535 return *Result;
3536 }
3537
3538 // Copy the candidates as our processing of them may load new declarations
3539 // from an external source and invalidate lookup_result.
3540 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3541
3542 for (NamedDecl *CandDecl : Candidates) {
3543 if (CandDecl->isInvalidDecl())
3544 continue;
3545
3547 auto CtorInfo = getConstructorInfo(Cand);
3548 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3551 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3552 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3553 else if (CtorInfo)
3554 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3555 llvm::ArrayRef(&Arg, NumArgs), OCS,
3556 /*SuppressUserConversions*/ true);
3557 else
3558 AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS,
3559 /*SuppressUserConversions*/ true);
3560 } else if (FunctionTemplateDecl *Tmpl =
3561 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3564 AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy,
3565 Classification,
3566 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3567 else if (CtorInfo)
3568 AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl,
3569 CtorInfo.FoundDecl, nullptr,
3570 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3571 else
3572 AddTemplateOverloadCandidate(Tmpl, Cand, nullptr,
3573 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3574 } else {
3575 assert(isa<UsingDecl>(Cand.getDecl()) &&
3576 "illegal Kind of operator = Decl");
3577 }
3578 }
3579
3581 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3582 case OR_Success:
3583 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3585 break;
3586
3587 case OR_Deleted:
3588 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3590 break;
3591
3592 case OR_Ambiguous:
3593 Result->setMethod(nullptr);
3595 break;
3596
3598 Result->setMethod(nullptr);
3600 break;
3601 }
3602
3603 return *Result;
3604}
3605
3606/// Look up the default constructor for the given class.
3610 false, false, false, false, false);
3611
3612 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3613}
3614
3615/// Look up the copying constructor for the given class.
3617 unsigned Quals) {
3618 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3619 "non-const, non-volatile qualifiers for copy ctor arg");
3622 Quals & Qualifiers::Volatile, false, false, false);
3623
3624 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3625}
3626
3627/// Look up the moving constructor for the given class.
3629 unsigned Quals) {
3632 Quals & Qualifiers::Volatile, false, false, false);
3633
3634 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3635}
3636
3637/// Look up the constructors for the given class.
3639 // If the implicit constructors have not yet been declared, do so now.
3641 runWithSufficientStackSpace(Class->getLocation(), [&] {
3642 if (Class->needsImplicitDefaultConstructor())
3643 DeclareImplicitDefaultConstructor(Class);
3644 if (Class->needsImplicitCopyConstructor())
3645 DeclareImplicitCopyConstructor(Class);
3646 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3647 DeclareImplicitMoveConstructor(Class);
3648 });
3649 }
3650
3653 return Class->lookup(Name);
3654}
3655
3656/// Look up the copying assignment operator for the given class.
3658 unsigned Quals, bool RValueThis,
3659 unsigned ThisQuals) {
3660 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3661 "non-const, non-volatile qualifiers for copy assignment arg");
3662 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3663 "non-const, non-volatile qualifiers for copy assignment this");
3666 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,
3667 ThisQuals & Qualifiers::Volatile);
3668
3669 return Result.getMethod();
3670}
3671
3672/// Look up the moving assignment operator for the given class.
3674 unsigned Quals,
3675 bool RValueThis,
3676 unsigned ThisQuals) {
3677 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3678 "non-const, non-volatile qualifiers for copy assignment this");
3681 Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const,
3682 ThisQuals & Qualifiers::Volatile);
3683
3684 return Result.getMethod();
3685}
3686
3687/// Look for the destructor of the given class.
3688///
3689/// During semantic analysis, this routine should be used in lieu of
3690/// CXXRecordDecl::getDestructor().
3691///
3692/// \returns The destructor for this class.
3694 return cast_or_null<CXXDestructorDecl>(
3696 false, false, false)
3697 .getMethod());
3698}
3699
3700/// LookupLiteralOperator - Determine which literal operator should be used for
3701/// a user-defined literal, per C++11 [lex.ext].
3702///
3703/// Normal overload resolution is not used to select which literal operator to
3704/// call for a user-defined literal. Look up the provided literal operator name,
3705/// and filter the results to the appropriate set for the given argument types.
3708 ArrayRef<QualType> ArgTys, bool AllowRaw,
3709 bool AllowTemplate, bool AllowStringTemplatePack,
3710 bool DiagnoseMissing, StringLiteral *StringLit) {
3711 LookupName(R, S);
3712 assert(R.getResultKind() != LookupResult::Ambiguous &&
3713 "literal operator lookup can't be ambiguous");
3714
3715 // Filter the lookup results appropriately.
3717
3718 bool AllowCooked = true;
3719 bool FoundRaw = false;
3720 bool FoundTemplate = false;
3721 bool FoundStringTemplatePack = false;
3722 bool FoundCooked = false;
3723
3724 while (F.hasNext()) {
3725 Decl *D = F.next();
3726 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3727 D = USD->getTargetDecl();
3728
3729 // If the declaration we found is invalid, skip it.
3730 if (D->isInvalidDecl()) {
3731 F.erase();
3732 continue;
3733 }
3734
3735 bool IsRaw = false;
3736 bool IsTemplate = false;
3737 bool IsStringTemplatePack = false;
3738 bool IsCooked = false;
3739
3740 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3741 if (FD->getNumParams() == 1 &&
3742 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3743 IsRaw = true;
3744 else if (FD->getNumParams() == ArgTys.size()) {
3745 IsCooked = true;
3746 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3747 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3748 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3749 IsCooked = false;
3750 break;
3751 }
3752 }
3753 }
3754 }
3755 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3756 TemplateParameterList *Params = FD->getTemplateParameters();
3757 if (Params->size() == 1) {
3758 IsTemplate = true;
3759 if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
3760 // Implied but not stated: user-defined integer and floating literals
3761 // only ever use numeric literal operator templates, not templates
3762 // taking a parameter of class type.
3763 F.erase();
3764 continue;
3765 }
3766
3767 // A string literal template is only considered if the string literal
3768 // is a well-formed template argument for the template parameter.
3769 if (StringLit) {
3770 SFINAETrap Trap(*this);
3771 SmallVector<TemplateArgument, 1> SugaredChecked, CanonicalChecked;
3772 TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);
3774 Params->getParam(0), Arg, FD, R.getNameLoc(), R.getNameLoc(),
3775 0, SugaredChecked, CanonicalChecked, CTAK_Specified) ||
3776 Trap.hasErrorOccurred())
3777 IsTemplate = false;
3778 }
3779 } else {
3780 IsStringTemplatePack = true;
3781 }
3782 }
3783
3784 if (AllowTemplate && StringLit && IsTemplate) {
3785 FoundTemplate = true;
3786 AllowRaw = false;
3787 AllowCooked = false;
3788 AllowStringTemplatePack = false;
3789 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3790 F.restart();
3791 FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3792 }
3793 } else if (AllowCooked && IsCooked) {
3794 FoundCooked = true;
3795 AllowRaw = false;
3796 AllowTemplate = StringLit;
3797 AllowStringTemplatePack = false;
3798 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3799 // Go through again and remove the raw and template decls we've
3800 // already found.
3801 F.restart();
3802 FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3803 }
3804 } else if (AllowRaw && IsRaw) {
3805 FoundRaw = true;
3806 } else if (AllowTemplate && IsTemplate) {
3807 FoundTemplate = true;
3808 } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3809 FoundStringTemplatePack = true;
3810 } else {
3811 F.erase();
3812 }
3813 }
3814
3815 F.done();
3816
3817 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3818 // form for string literal operator templates.
3819 if (StringLit && FoundTemplate)
3820 return LOLR_Template;
3821
3822 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3823 // parameter type, that is used in preference to a raw literal operator
3824 // or literal operator template.
3825 if (FoundCooked)
3826 return LOLR_Cooked;
3827
3828 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3829 // operator template, but not both.
3830 if (FoundRaw && FoundTemplate) {
3831 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3832 for (const NamedDecl *D : R)
3834 return LOLR_Error;
3835 }
3836
3837 if (FoundRaw)
3838 return LOLR_Raw;
3839
3840 if (FoundTemplate)
3841 return LOLR_Template;
3842
3843 if (FoundStringTemplatePack)
3845
3846 // Didn't find anything we could use.
3847 if (DiagnoseMissing) {
3848 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3849 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3850 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3851 << (AllowTemplate || AllowStringTemplatePack);
3852 return LOLR_Error;
3853 }
3854
3856}
3857
3859 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3860
3861 // If we haven't yet seen a decl for this key, or the last decl
3862 // was exactly this one, we're done.
3863 if (Old == nullptr || Old == New) {
3864 Old = New;
3865 return;
3866 }
3867
3868 // Otherwise, decide which is a more recent redeclaration.
3869 FunctionDecl *OldFD = Old->getAsFunction();
3870 FunctionDecl *NewFD = New->getAsFunction();
3871
3872 FunctionDecl *Cursor = NewFD;
3873 while (true) {
3874 Cursor = Cursor->getPreviousDecl();
3875
3876 // If we got to the end without finding OldFD, OldFD is the newer
3877 // declaration; leave things as they are.
3878 if (!Cursor) return;
3879
3880 // If we do find OldFD, then NewFD is newer.
3881 if (Cursor == OldFD) break;
3882
3883 // Otherwise, keep looking.
3884 }
3885
3886 Old = New;
3887}
3888
3891 // Find all of the associated namespaces and classes based on the
3892 // arguments we have.
3893 AssociatedNamespaceSet AssociatedNamespaces;
3894 AssociatedClassSet AssociatedClasses;
3896 AssociatedNamespaces,
3897 AssociatedClasses);
3898
3899 // C++ [basic.lookup.argdep]p3:
3900 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3901 // and let Y be the lookup set produced by argument dependent
3902 // lookup (defined as follows). If X contains [...] then Y is
3903 // empty. Otherwise Y is the set of declarations found in the
3904 // namespaces associated with the argument types as described
3905 // below. The set of declarations found by the lookup of the name
3906 // is the union of X and Y.
3907 //
3908 // Here, we compute Y and add its members to the overloaded
3909 // candidate set.
3910 for (auto *NS : AssociatedNamespaces) {
3911 // When considering an associated namespace, the lookup is the
3912 // same as the lookup performed when the associated namespace is
3913 // used as a qualifier (3.4.3.2) except that:
3914 //
3915 // -- Any using-directives in the associated namespace are
3916 // ignored.
3917 //
3918 // -- Any namespace-scope friend functions declared in
3919 // associated classes are visible within their respective
3920 // namespaces even if they are not visible during an ordinary
3921 // lookup (11.4).
3922 //
3923 // C++20 [basic.lookup.argdep] p4.3
3924 // -- are exported, are attached to a named module M, do not appear
3925 // in the translation unit containing the point of the lookup, and
3926 // have the same innermost enclosing non-inline namespace scope as
3927 // a declaration of an associated entity attached to M.
3928 DeclContext::lookup_result R = NS->lookup(Name);
3929 for (auto *D : R) {
3930 auto *Underlying = D;
3931 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3932 Underlying = USD->getTargetDecl();
3933
3934 if (!isa<FunctionDecl>(Underlying) &&
3935 !isa<FunctionTemplateDecl>(Underlying))
3936 continue;
3937
3938 // The declaration is visible to argument-dependent lookup if either
3939 // it's ordinarily visible or declared as a friend in an associated
3940 // class.
3941 bool Visible = false;
3942 for (D = D->getMostRecentDecl(); D;
3943 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3945 if (isVisible(D)) {
3946 Visible = true;
3947 break;
3948 }
3949
3950 if (!getLangOpts().CPlusPlusModules)
3951 continue;
3952
3953 if (D->isInExportDeclContext()) {
3954 Module *FM = D->getOwningModule();
3955 // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
3956 // exports are only valid in module purview and outside of any
3957 // PMF (although a PMF should not even be present in a module
3958 // with an import).
3959 assert(FM && FM->isNamedModule() && !FM->isPrivateModule() &&
3960 "bad export context");
3961 // .. are attached to a named module M, do not appear in the
3962 // translation unit containing the point of the lookup..
3963 if (D->isInAnotherModuleUnit() &&
3964 llvm::any_of(AssociatedClasses, [&](auto *E) {
3965 // ... and have the same innermost enclosing non-inline
3966 // namespace scope as a declaration of an associated entity
3967 // attached to M
3968 if (E->getOwningModule() != FM)
3969 return false;
3970 // TODO: maybe this could be cached when generating the
3971 // associated namespaces / entities.
3972 DeclContext *Ctx = E->getDeclContext();
3973 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
3974 Ctx = Ctx->getParent();
3975 return Ctx == NS;
3976 })) {
3977 Visible = true;
3978 break;
3979 }
3980 }
3981 } else if (D->getFriendObjectKind()) {
3982 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3983 // [basic.lookup.argdep]p4:
3984 // Argument-dependent lookup finds all declarations of functions and
3985 // function templates that
3986 // - ...
3987 // - are declared as a friend ([class.friend]) of any class with a
3988 // reachable definition in the set of associated entities,
3989 //
3990 // FIXME: If there's a merged definition of D that is reachable, then
3991 // the friend declaration should be considered.
3992 if (AssociatedClasses.count(RD) && isReachable(D)) {
3993 Visible = true;
3994 break;
3995 }
3996 }
3997 }
3998
3999 // FIXME: Preserve D as the FoundDecl.
4000 if (Visible)
4001 Result.insert(Underlying);
4002 }
4003 }
4004}
4005
4006//----------------------------------------------------------------------------
4007// Search for all visible declarations.
4008//----------------------------------------------------------------------------
4010
4011bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
4012
4013namespace {
4014
4015class ShadowContextRAII;
4016
4017class VisibleDeclsRecord {
4018public:
4019 /// An entry in the shadow map, which is optimized to store a
4020 /// single declaration (the common case) but can also store a list
4021 /// of declarations.
4022 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
4023
4024private:
4025 /// A mapping from declaration names to the declarations that have
4026 /// this name within a particular scope.
4027 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
4028
4029 /// A list of shadow maps, which is used to model name hiding.
4030 std::list<ShadowMap> ShadowMaps;
4031
4032 /// The declaration contexts we have already visited.
4034
4035 friend class ShadowContextRAII;
4036
4037public:
4038 /// Determine whether we have already visited this context
4039 /// (and, if not, note that we are going to visit that context now).
4040 bool visitedContext(DeclContext *Ctx) {
4041 return !VisitedContexts.insert(Ctx).second;
4042 }
4043
4044 bool alreadyVisitedContext(DeclContext *Ctx) {
4045 return VisitedContexts.count(Ctx);
4046 }
4047
4048 /// Determine whether the given declaration is hidden in the
4049 /// current scope.
4050 ///
4051 /// \returns the declaration that hides the given declaration, or
4052 /// NULL if no such declaration exists.
4053 NamedDecl *checkHidden(NamedDecl *ND);
4054
4055 /// Add a declaration to the current shadow map.
4056 void add(NamedDecl *ND) {
4057 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
4058 }
4059};
4060
4061/// RAII object that records when we've entered a shadow context.
4062class ShadowContextRAII {
4063 VisibleDeclsRecord &Visible;
4064
4065 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
4066
4067public:
4068 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
4069 Visible.ShadowMaps.emplace_back();
4070 }
4071
4072 ~ShadowContextRAII() {
4073 Visible.ShadowMaps.pop_back();
4074 }
4075};
4076
4077} // end anonymous namespace
4078
4079NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
4080 unsigned IDNS = ND->getIdentifierNamespace();
4081 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
4082 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
4083 SM != SMEnd; ++SM) {
4084 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
4085 if (Pos == SM->end())
4086 continue;
4087
4088 for (auto *D : Pos->second) {
4089 // A tag declaration does not hide a non-tag declaration.
4090 if (D->hasTagIdentifierNamespace() &&
4093 continue;
4094
4095 // Protocols are in distinct namespaces from everything else.
4097 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
4098 D->getIdentifierNamespace() != IDNS)
4099 continue;
4100
4101 // Functions and function templates in the same scope overload
4102 // rather than hide. FIXME: Look for hiding based on function
4103 // signatures!
4106 SM == ShadowMaps.rbegin())
4107 continue;
4108
4109 // A shadow declaration that's created by a resolved using declaration
4110 // is not hidden by the same using declaration.
4111 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
4112 cast<UsingShadowDecl>(ND)->getIntroducer() == D)
4113 continue;
4114
4115 // We've found a declaration that hides this one.
4116 return D;
4117 }
4118 }
4119
4120 return nullptr;
4121}
4122
4123namespace {
4124class LookupVisibleHelper {
4125public:
4126 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
4127 bool LoadExternal)
4128 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
4129 LoadExternal(LoadExternal) {}
4130
4131 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
4132 bool IncludeGlobalScope) {
4133 // Determine the set of using directives available during
4134 // unqualified name lookup.
4135 Scope *Initial = S;
4136 UnqualUsingDirectiveSet UDirs(SemaRef);
4137 if (SemaRef.getLangOpts().CPlusPlus) {
4138 // Find the first namespace or translation-unit scope.
4139 while (S && !isNamespaceOrTranslationUnitScope(S))
4140 S = S->getParent();
4141
4142 UDirs.visitScopeChain(Initial, S);
4143 }
4144 UDirs.done();
4145
4146 // Look for visible declarations.
4147 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4148 Result.setAllowHidden(Consumer.includeHiddenDecls());
4149 if (!IncludeGlobalScope)
4150 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4151 ShadowContextRAII Shadow(Visited);
4152 lookupInScope(Initial, Result, UDirs);
4153 }
4154
4155 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
4156 Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
4157 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4158 Result.setAllowHidden(Consumer.includeHiddenDecls());
4159 if (!IncludeGlobalScope)
4160 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4161
4162 ShadowContextRAII Shadow(Visited);
4163 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
4164 /*InBaseClass=*/false);
4165 }
4166
4167private:
4168 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
4169 bool QualifiedNameLookup, bool InBaseClass) {
4170 if (!Ctx)
4171 return;
4172
4173 // Make sure we don't visit the same context twice.
4174 if (Visited.visitedContext(Ctx->getPrimaryContext()))
4175 return;
4176
4177 Consumer.EnteredContext(Ctx);
4178
4179 // Outside C++, lookup results for the TU live on identifiers.
4180 if (isa<TranslationUnitDecl>(Ctx) &&
4181 !Result.getSema().getLangOpts().CPlusPlus) {
4182 auto &S = Result.getSema();
4183 auto &Idents = S.Context.Idents;
4184
4185 // Ensure all external identifiers are in the identifier table.
4186 if (LoadExternal)
4188 Idents.getExternalIdentifierLookup()) {
4189 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4190 for (StringRef Name = Iter->Next(); !Name.empty();
4191 Name = Iter->Next())
4192 Idents.get(Name);
4193 }
4194
4195 // Walk all lookup results in the TU for each identifier.
4196 for (const auto &Ident : Idents) {
4197 for (auto I = S.IdResolver.begin(Ident.getValue()),
4198 E = S.IdResolver.end();
4199 I != E; ++I) {
4200 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
4201 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
4202 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4203 Visited.add(ND);
4204 }
4205 }
4206 }
4207 }
4208
4209 return;
4210 }
4211
4212 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
4213 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4214
4216 // We sometimes skip loading namespace-level results (they tend to be huge).
4217 bool Load = LoadExternal ||
4218 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
4219 // Enumerate all of the results in this context.
4221 Load ? Ctx->lookups()
4222 : Ctx->noload_lookups(/*PreserveInternalState=*/false))
4223 for (auto *D : R)
4224 // Rather than visit immediately, we put ND into a vector and visit
4225 // all decls, in order, outside of this loop. The reason is that
4226 // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)
4227 // may invalidate the iterators used in the two
4228 // loops above.
4229 DeclsToVisit.push_back(D);
4230
4231 for (auto *D : DeclsToVisit)
4232 if (auto *ND = Result.getAcceptableDecl(D)) {
4233 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4234 Visited.add(ND);
4235 }
4236
4237 DeclsToVisit.clear();
4238
4239 // Traverse using directives for qualified name lookup.
4240 if (QualifiedNameLookup) {
4241 ShadowContextRAII Shadow(Visited);
4242 for (auto *I : Ctx->using_directives()) {
4243 if (!Result.getSema().isVisible(I))
4244 continue;
4245 lookupInDeclContext(I->getNominatedNamespace(), Result,
4246 QualifiedNameLookup, InBaseClass);
4247 }
4248 }
4249
4250 // Traverse the contexts of inherited C++ classes.
4251 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
4252 if (!Record->hasDefinition())
4253 return;
4254
4255 for (const auto &B : Record->bases()) {
4256 QualType BaseType = B.getType();
4257
4258 RecordDecl *RD;
4259 if (BaseType->isDependentType()) {
4260 if (!IncludeDependentBases) {
4261 // Don't look into dependent bases, because name lookup can't look
4262 // there anyway.
4263 continue;
4264 }
4265 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
4266 if (!TST)
4267 continue;
4268 TemplateName TN = TST->getTemplateName();
4269 const auto *TD =
4270 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
4271 if (!TD)
4272 continue;
4273 RD = TD->getTemplatedDecl();
4274 } else {
4275 const auto *Record = BaseType->getAs<RecordType>();
4276 if (!Record)
4277 continue;
4278 RD = Record->getDecl();
4279 }
4280
4281 // FIXME: It would be nice to be able to determine whether referencing
4282 // a particular member would be ambiguous. For example, given
4283 //
4284 // struct A { int member; };
4285 // struct B { int member; };
4286 // struct C : A, B { };
4287 //
4288 // void f(C *c) { c->### }
4289 //
4290 // accessing 'member' would result in an ambiguity. However, we
4291 // could be smart enough to qualify the member with the base
4292 // class, e.g.,
4293 //
4294 // c->B::member
4295 //
4296 // or
4297 //
4298 // c->A::member
4299
4300 // Find results in this base class (and its bases).
4301 ShadowContextRAII Shadow(Visited);
4302 lookupInDeclContext(RD, Result, QualifiedNameLookup,
4303 /*InBaseClass=*/true);
4304 }
4305 }
4306
4307 // Traverse the contexts of Objective-C classes.
4308 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
4309 // Traverse categories.
4310 for (auto *Cat : IFace->visible_categories()) {
4311 ShadowContextRAII Shadow(Visited);
4312 lookupInDeclContext(Cat, Result, QualifiedNameLookup,
4313 /*InBaseClass=*/false);
4314 }
4315
4316 // Traverse protocols.
4317 for (auto *I : IFace->all_referenced_protocols()) {
4318 ShadowContextRAII Shadow(Visited);
4319 lookupInDeclContext(I, Result, QualifiedNameLookup,
4320 /*InBaseClass=*/false);
4321 }
4322
4323 // Traverse the superclass.
4324 if (IFace->getSuperClass()) {
4325 ShadowContextRAII Shadow(Visited);
4326 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
4327 /*InBaseClass=*/true);
4328 }
4329
4330 // If there is an implementation, traverse it. We do this to find
4331 // synthesized ivars.
4332 if (IFace->getImplementation()) {
4333 ShadowContextRAII Shadow(Visited);
4334 lookupInDeclContext(IFace->getImplementation(), Result,
4335 QualifiedNameLookup, InBaseClass);
4336 }
4337 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
4338 for (auto *I : Protocol->protocols()) {
4339 ShadowContextRAII Shadow(Visited);
4340 lookupInDeclContext(I, Result, QualifiedNameLookup,
4341 /*InBaseClass=*/false);
4342 }
4343 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
4344 for (auto *I : Category->protocols()) {
4345 ShadowContextRAII Shadow(Visited);
4346 lookupInDeclContext(I, Result, QualifiedNameLookup,
4347 /*InBaseClass=*/false);
4348 }
4349
4350 // If there is an implementation, traverse it.
4351 if (Category->getImplementation()) {
4352 ShadowContextRAII Shadow(Visited);
4353 lookupInDeclContext(Category->getImplementation(), Result,
4354 QualifiedNameLookup, /*InBaseClass=*/true);
4355 }
4356 }
4357 }
4358
4359 void lookupInScope(Scope *S, LookupResult &Result,
4360 UnqualUsingDirectiveSet &UDirs) {
4361 // No clients run in this mode and it's not supported. Please add tests and
4362 // remove the assertion if you start relying on it.
4363 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4364
4365 if (!S)
4366 return;
4367
4368 if (!S->getEntity() ||
4369 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4370 (S->getEntity())->isFunctionOrMethod()) {
4371 FindLocalExternScope FindLocals(Result);
4372 // Walk through the declarations in this Scope. The consumer might add new
4373 // decls to the scope as part of deserialization, so make a copy first.
4374 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4375 for (Decl *D : ScopeDecls) {
4376 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
4377 if ((ND = Result.getAcceptableDecl(ND))) {
4378 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
4379 Visited.add(ND);
4380 }
4381 }
4382 }
4383
4384 DeclContext *Entity = S->getLookupEntity();
4385 if (Entity) {
4386 // Look into this scope's declaration context, along with any of its
4387 // parent lookup contexts (e.g., enclosing classes), up to the point
4388 // where we hit the context stored in the next outer scope.
4389 DeclContext *OuterCtx = findOuterContext(S);
4390
4391 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
4392 Ctx = Ctx->getLookupParent()) {
4393 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
4394 if (Method->isInstanceMethod()) {
4395 // For instance methods, look for ivars in the method's interface.
4396 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4397 Result.getNameLoc(),
4399 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4400 lookupInDeclContext(IFace, IvarResult,
4401 /*QualifiedNameLookup=*/false,
4402 /*InBaseClass=*/false);
4403 }
4404 }
4405
4406 // We've already performed all of the name lookup that we need
4407 // to for Objective-C methods; the next context will be the
4408 // outer scope.
4409 break;
4410 }
4411
4412 if (Ctx->isFunctionOrMethod())
4413 continue;
4414
4415 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4416 /*InBaseClass=*/false);
4417 }
4418 } else if (!S->getParent()) {
4419 // Look into the translation unit scope. We walk through the translation
4420 // unit's declaration context, because the Scope itself won't have all of
4421 // the declarations if we loaded a precompiled header.
4422 // FIXME: We would like the translation unit's Scope object to point to
4423 // the translation unit, so we don't need this special "if" branch.
4424 // However, doing so would force the normal C++ name-lookup code to look
4425 // into the translation unit decl when the IdentifierInfo chains would
4426 // suffice. Once we fix that problem (which is part of a more general
4427 // "don't look in DeclContexts unless we have to" optimization), we can
4428 // eliminate this.
4429 Entity = Result.getSema().Context.getTranslationUnitDecl();
4430 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
4431 /*InBaseClass=*/false);
4432 }
4433
4434 if (Entity) {
4435 // Lookup visible declarations in any namespaces found by using
4436 // directives.
4437 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4438 lookupInDeclContext(
4439 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4440 /*QualifiedNameLookup=*/false,
4441 /*InBaseClass=*/false);
4442 }
4443
4444 // Lookup names in the parent scope.
4445 ShadowContextRAII Shadow(Visited);
4446 lookupInScope(S->getParent(), Result, UDirs);
4447 }
4448
4449private:
4450 VisibleDeclsRecord Visited;
4451 VisibleDeclConsumer &Consumer;
4452 bool IncludeDependentBases;
4453 bool LoadExternal;
4454};
4455} // namespace
4456
4458 VisibleDeclConsumer &Consumer,
4459 bool IncludeGlobalScope, bool LoadExternal) {
4460 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4461 LoadExternal);
4462 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4463}
4464
4466 VisibleDeclConsumer &Consumer,
4467 bool IncludeGlobalScope,
4468 bool IncludeDependentBases, bool LoadExternal) {
4469 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4470 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4471}
4472
4473/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
4474/// If GnuLabelLoc is a valid source location, then this is a definition
4475/// of an __label__ label name, otherwise it is a normal label definition
4476/// or use.
4478 SourceLocation GnuLabelLoc) {
4479 // Do a lookup to see if we have a label with this name already.
4480 NamedDecl *Res = nullptr;
4481
4482 if (GnuLabelLoc.isValid()) {
4483 // Local label definitions always shadow existing labels.
4484 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4485 Scope *S = CurScope;
4486 PushOnScopeChains(Res, S, true);
4487 return cast<LabelDecl>(Res);
4488 }
4489
4490 // Not a GNU local label.
4491 Res = LookupSingleName(CurScope, II, Loc, LookupLabel,
4492 RedeclarationKind::NotForRedeclaration);
4493 // If we found a label, check to see if it is in the same context as us.
4494 // When in a Block, we don't want to reuse a label in an enclosing function.
4495 if (Res && Res->getDeclContext() != CurContext)
4496 Res = nullptr;
4497 if (!Res) {
4498 // If not forward referenced or defined already, create the backing decl.
4500 Scope *S = CurScope->getFnParent();
4501 assert(S && "Not in a function?");
4502 PushOnScopeChains(Res, S, true);
4503 }
4504 return cast<LabelDecl>(Res);
4505}
4506
4507//===----------------------------------------------------------------------===//
4508// Typo correction
4509//===----------------------------------------------------------------------===//
4510
4512 TypoCorrection &Candidate) {
4513 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4514 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4515}
4516
4517static void LookupPotentialTypoResult(Sema &SemaRef,
4518 LookupResult &Res,
4519 IdentifierInfo *Name,
4520 Scope *S, CXXScopeSpec *SS,
4521 DeclContext *MemberContext,
4522 bool EnteringContext,
4523 bool isObjCIvarLookup,
4524 bool FindHidden);
4525
4526/// Check whether the declarations found for a typo correction are
4527/// visible. Set the correction's RequiresImport flag to true if none of the
4528/// declarations are visible, false otherwise.
4530 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4531
4532 for (/**/; DI != DE; ++DI)
4533 if (!LookupResult::isVisible(SemaRef, *DI))
4534 break;
4535 // No filtering needed if all decls are visible.
4536 if (DI == DE) {
4537 TC.setRequiresImport(false);
4538 return;
4539 }
4540
4541 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4542 bool AnyVisibleDecls = !NewDecls.empty();
4543
4544 for (/**/; DI != DE; ++DI) {
4545 if (LookupResult::isVisible(SemaRef, *DI)) {
4546 if (!AnyVisibleDecls) {
4547 // Found a visible decl, discard all hidden ones.
4548 AnyVisibleDecls = true;
4549 NewDecls.clear();
4550 }
4551 NewDecls.push_back(*DI);
4552 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4553 NewDecls.push_back(*DI);
4554 }
4555
4556 if (NewDecls.empty())
4557 TC = TypoCorrection();
4558 else {
4559 TC.setCorrectionDecls(NewDecls);
4560 TC.setRequiresImport(!AnyVisibleDecls);
4561 }
4562}
4563
4564// Fill the supplied vector with the IdentifierInfo pointers for each piece of
4565// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4566// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4570 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4571 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4572 else
4573 Identifiers.clear();
4574
4575 const IdentifierInfo *II = nullptr;
4576
4577 switch (NNS->getKind()) {
4579 II = NNS->getAsIdentifier();
4580 break;
4581
4584 return;
4585 II = NNS->getAsNamespace()->getIdentifier();
4586 break;
4587
4589 II = NNS->getAsNamespaceAlias()->getIdentifier();
4590 break;
4591
4594 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4595 break;
4596
4599 return;
4600 }
4601
4602 if (II)
4603 Identifiers.push_back(II);
4604}
4605
4607 DeclContext *Ctx, bool InBaseClass) {
4608 // Don't consider hidden names for typo correction.
4609 if (Hiding)
4610 return;
4611
4612 // Only consider entities with identifiers for names, ignoring
4613 // special names (constructors, overloaded operators, selectors,
4614 // etc.).
4615 IdentifierInfo *Name = ND->getIdentifier();
4616 if (!Name)
4617 return;
4618
4619 // Only consider visible declarations and declarations from modules with
4620 // names that exactly match.
4621 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4622 return;
4623
4624 FoundName(Name->getName());
4625}
4626
4628 // Compute the edit distance between the typo and the name of this
4629 // entity, and add the identifier to the list of results.
4630 addName(Name, nullptr);
4631}
4632
4634 // Compute the edit distance between the typo and this keyword,
4635 // and add the keyword to the list of results.
4636 addName(Keyword, nullptr, nullptr, true);
4637}
4638
4639void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4640 NestedNameSpecifier *NNS, bool isKeyword) {
4641 // Use a simple length-based heuristic to determine the minimum possible
4642 // edit distance. If the minimum isn't good enough, bail out early.
4643 StringRef TypoStr = Typo->getName();
4644 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4645 if (MinED && TypoStr.size() / MinED < 3)
4646 return;
4647
4648 // Compute an upper bound on the allowable edit distance, so that the
4649 // edit-distance algorithm can short-circuit.
4650 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4651 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4652 if (ED > UpperBound) return;
4653
4654 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4655 if (isKeyword) TC.makeKeyword();
4656 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4657 addCorrection(TC);
4658}
4659
4660static const unsigned MaxTypoDistanceResultSets = 5;
4661
4663 StringRef TypoStr = Typo->getName();
4664 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4665
4666 // For very short typos, ignore potential corrections that have a different
4667 // base identifier from the typo or which have a normalized edit distance
4668 // longer than the typo itself.
4669 if (TypoStr.size() < 3 &&
4670 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4671 return;
4672
4673 // If the correction is resolved but is not viable, ignore it.
4674 if (Correction.isResolved()) {
4675 checkCorrectionVisibility(SemaRef, Correction);
4676 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4677 return;
4678 }
4679
4680 TypoResultList &CList =
4681 CorrectionResults[Correction.getEditDistance(false)][Name];
4682
4683 if (!CList.empty() && !CList.back().isResolved())
4684 CList.pop_back();
4685 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4686 auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
4687 return TypoCorr.getCorrectionDecl() == NewND;
4688 });
4689 if (RI != CList.end()) {
4690 // The Correction refers to a decl already in the list. No insertion is
4691 // necessary and all further cases will return.
4692
4693 auto IsDeprecated = [](Decl *D) {
4694 while (D) {
4695 if (D->isDeprecated())
4696 return true;
4697 D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
4698 }
4699 return false;
4700 };
4701
4702 // Prefer non deprecated Corrections over deprecated and only then
4703 // sort using an alphabetical order.
4704 std::pair<bool, std::string> NewKey = {
4705 IsDeprecated(Correction.getFoundDecl()),
4706 Correction.getAsString(SemaRef.getLangOpts())};
4707
4708 std::pair<bool, std::string> PrevKey = {
4709 IsDeprecated(RI->getFoundDecl()),
4710 RI->getAsString(SemaRef.getLangOpts())};
4711
4712 if (NewKey < PrevKey)
4713 *RI = Correction;
4714 return;
4715 }
4716 }
4717 if (CList.empty() || Correction.isResolved())
4718 CList.push_back(Correction);
4719
4720 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4721 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4722}
4723
4725 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4726 SearchNamespaces = true;
4727
4728 for (auto KNPair : KnownNamespaces)
4729 Namespaces.addNameSpecifier(KNPair.first);
4730
4731 bool SSIsTemplate = false;
4732 if (NestedNameSpecifier *NNS =
4733 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4734 if (const Type *T = NNS->getAsType())
4735 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4736 }
4737 // Do not transform this into an iterator-based loop. The loop body can
4738 // trigger the creation of further types (through lazy deserialization) and
4739 // invalid iterators into this list.
4740 auto &Types = SemaRef.getASTContext().getTypes();
4741 for (unsigned I = 0; I != Types.size(); ++I) {
4742 const auto *TI = Types[I];
4743 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4744 CD = CD->getCanonicalDecl();
4745 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4746 !CD->isUnion() && CD->getIdentifier() &&
4747 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4748 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4749 Namespaces.addNameSpecifier(CD);
4750 }
4751 }
4752}
4753
4755 if (++CurrentTCIndex < ValidatedCorrections.size())
4756 return ValidatedCorrections[CurrentTCIndex];
4757
4758 CurrentTCIndex = ValidatedCorrections.size();
4759 while (!CorrectionResults.empty()) {
4760 auto DI = CorrectionResults.begin();
4761 if (DI->second.empty()) {
4762 CorrectionResults.erase(DI);
4763 continue;
4764 }
4765
4766 auto RI = DI->second.begin();
4767 if (RI->second.empty()) {
4768 DI->second.erase(RI);
4769 performQualifiedLookups();
4770 continue;
4771 }
4772
4773 TypoCorrection TC = RI->second.pop_back_val();
4774 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4775 ValidatedCorrections.push_back(TC);
4776 return ValidatedCorrections[CurrentTCIndex];
4777 }
4778 }
4779 return ValidatedCorrections[0]; // The empty correction.
4780}
4781
4782bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4784 DeclContext *TempMemberContext = MemberContext;
4785 CXXScopeSpec *TempSS = SS.get();
4786retry_lookup:
4787 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4788 EnteringContext,
4789 CorrectionValidator->IsObjCIvarLookup,
4790 Name == Typo && !Candidate.WillReplaceSpecifier());
4791 switch (Result.getResultKind()) {
4795 if (TempSS) {
4796 // Immediately retry the lookup without the given CXXScopeSpec
4797 TempSS = nullptr;
4798 Candidate.WillReplaceSpecifier(true);
4799 goto retry_lookup;
4800 }
4801 if (TempMemberContext) {
4802 if (SS && !TempSS)
4803 TempSS = SS.get();
4804 TempMemberContext = nullptr;
4805 goto retry_lookup;
4806 }
4807 if (SearchNamespaces)
4808 QualifiedResults.push_back(Candidate);
4809 break;
4810
4812 // We don't deal with ambiguities.
4813 break;
4814
4817 // Store all of the Decls for overloaded symbols
4818 for (auto *TRD : Result)
4819 Candidate.addCorrectionDecl(TRD);
4820 checkCorrectionVisibility(SemaRef, Candidate);
4821 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4822 if (SearchNamespaces)
4823 QualifiedResults.push_back(Candidate);
4824 break;
4825 }
4826 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4827 return true;
4828 }
4829 return false;
4830}
4831
4832void TypoCorrectionConsumer::performQualifiedLookups() {
4833 unsigned TypoLen = Typo->getName().size();
4834 for (const TypoCorrection &QR : QualifiedResults) {
4835 for (const auto &NSI : Namespaces) {
4836 DeclContext *Ctx = NSI.DeclCtx;
4837 const Type *NSType = NSI.NameSpecifier->getAsType();
4838
4839 // If the current NestedNameSpecifier refers to a class and the
4840 // current correction candidate is the name of that class, then skip
4841 // it as it is unlikely a qualified version of the class' constructor
4842 // is an appropriate correction.
4843 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4844 nullptr) {
4845 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4846 continue;
4847 }
4848
4849 TypoCorrection TC(QR);
4850 TC.ClearCorrectionDecls();
4851 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4852 TC.setQualifierDistance(NSI.EditDistance);
4853 TC.setCallbackDistance(0); // Reset the callback distance
4854
4855 // If the current correction candidate and namespace combination are
4856 // too far away from the original typo based on the normalized edit
4857 // distance, then skip performing a qualified name lookup.
4858 unsigned TmpED = TC.getEditDistance(true);
4859 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4860 TypoLen / TmpED < 3)
4861 continue;
4862
4863 Result.clear();
4864 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4865 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4866 continue;
4867
4868 // Any corrections added below will be validated in subsequent
4869 // iterations of the main while() loop over the Consumer's contents.
4870 switch (Result.getResultKind()) {
4873 if (SS && SS->isValid()) {
4874 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4875 std::string OldQualified;
4876 llvm::raw_string_ostream OldOStream(OldQualified);
4877 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4878 OldOStream << Typo->getName();
4879 // If correction candidate would be an identical written qualified
4880 // identifier, then the existing CXXScopeSpec probably included a
4881 // typedef that didn't get accounted for properly.
4882 if (OldOStream.str() == NewQualified)
4883 break;
4884 }
4885 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4886 TRD != TRDEnd; ++TRD) {
4887 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4888 NSType ? NSType->getAsCXXRecordDecl()
4889 : nullptr,
4890 TRD.getPair()) == Sema::AR_accessible)
4891 TC.addCorrectionDecl(*TRD);
4892 }
4893 if (TC.isResolved()) {
4894 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4895 addCorrection(TC);
4896 }
4897 break;
4898 }
4903 break;
4904 }
4905 }
4906 }
4907 QualifiedResults.clear();
4908}
4909
4910TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4911 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4912 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4913 if (NestedNameSpecifier *NNS =
4914 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4915 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4916 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4917
4918 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4919 }
4920 // Build the list of identifiers that would be used for an absolute
4921 // (from the global context) NestedNameSpecifier referring to the current
4922 // context.
4923 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4924 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4925 CurContextIdentifiers.push_back(ND->getIdentifier());
4926 }
4927
4928 // Add the global context as a NestedNameSpecifier
4929 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4931 DistanceMap[1].push_back(SI);
4932}
4933
4934auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4935 DeclContext *Start) -> DeclContextList {
4936 assert(Start && "Building a context chain from a null context");
4937 DeclContextList Chain;
4938 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4939 DC = DC->getLookupParent()) {
4940 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4941 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4942 !(ND && ND->isAnonymousNamespace()))
4943 Chain.push_back(DC->getPrimaryContext());
4944 }
4945 return Chain;
4946}
4947
4948unsigned
4949TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4950 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4951 unsigned NumSpecifiers = 0;
4952 for (DeclContext *C : llvm::reverse(DeclChain)) {
4953 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4954 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4955 ++NumSpecifiers;
4956 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4957 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4958 RD->getTypeForDecl());
4959 ++NumSpecifiers;
4960 }
4961 }
4962 return NumSpecifiers;
4963}
4964
4965void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4966 DeclContext *Ctx) {
4967 NestedNameSpecifier *NNS = nullptr;
4968 unsigned NumSpecifiers = 0;
4969 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4970 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4971
4972 // Eliminate common elements from the two DeclContext chains.
4973 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4974 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4975 break;
4976 NamespaceDeclChain.pop_back();
4977 }
4978
4979 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4980 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4981
4982 // Add an explicit leading '::' specifier if needed.
4983 if (NamespaceDeclChain.empty()) {
4984 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4986 NumSpecifiers =
4987 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4988 } else if (NamedDecl *ND =
4989 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4990 IdentifierInfo *Name = ND->getIdentifier();
4991 bool SameNameSpecifier = false;
4992 if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
4993 std::string NewNameSpecifier;
4994 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4995 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4996 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4997 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4998 SpecifierOStream.flush();
4999 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
5000 }
5001 if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
5002 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
5004 NumSpecifiers =
5005 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
5006 }
5007 }
5008
5009 // If the built NestedNameSpecifier would be replacing an existing
5010 // NestedNameSpecifier, use the number of component identifiers that
5011 // would need to be changed as the edit distance instead of the number
5012 // of components in the built NestedNameSpecifier.
5013 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
5014 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
5015 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
5016 NumSpecifiers =
5017 llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers),
5018 llvm::ArrayRef(NewNameSpecifierIdentifiers));
5019 }
5020
5021 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
5022 DistanceMap[NumSpecifiers].push_back(SI);
5023}
5024
5025/// Perform name lookup for a possible result for typo correction.
5026static void LookupPotentialTypoResult(Sema &SemaRef,
5027 LookupResult &Res,
5028 IdentifierInfo *Name,
5029 Scope *S, CXXScopeSpec *SS,
5030 DeclContext *MemberContext,
5031 bool EnteringContext,
5032 bool isObjCIvarLookup,
5033 bool FindHidden) {
5034 Res.suppressDiagnostics();
5035 Res.clear();
5036 Res.setLookupName(Name);
5037 Res.setAllowHidden(FindHidden);
5038 if (MemberContext) {
5039 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
5040 if (isObjCIvarLookup) {
5041 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
5042 Res.addDecl(Ivar);
5043 Res.resolveKind();
5044 return;
5045 }
5046 }
5047
5048 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
5050 Res.addDecl(Prop);
5051 Res.resolveKind();
5052 return;
5053 }
5054 }
5055
5056 SemaRef.LookupQualifiedName(Res, MemberContext);
5057 return;
5058 }
5059
5060 SemaRef.LookupParsedName(Res, S, SS,
5061 /*ObjectType=*/QualType(),
5062 /*AllowBuiltinCreation=*/false, EnteringContext);
5063
5064 // Fake ivar lookup; this should really be part of
5065 // LookupParsedName.
5066 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
5067 if (Method->isInstanceMethod() && Method->getClassInterface() &&
5068 (Res.empty() ||
5069 (Res.isSingleResult() &&
5071 if (ObjCIvarDecl *IV
5072 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
5073 Res.addDecl(IV);
5074 Res.resolveKind();
5075 }
5076 }
5077 }
5078}
5079
5080/// Add keywords to the consumer as possible typo corrections.
5081static void AddKeywordsToConsumer(Sema &SemaRef,
5082 TypoCorrectionConsumer &Consumer,
5084 bool AfterNestedNameSpecifier) {
5085 if (AfterNestedNameSpecifier) {
5086 // For 'X::', we know exactly which keywords can appear next.
5087 Consumer.addKeywordResult("template");
5088 if (CCC.WantExpressionKeywords)
5089 Consumer.addKeywordResult("operator");
5090 return;
5091 }
5092
5093 if (CCC.WantObjCSuper)
5094 Consumer.addKeywordResult("super");
5095
5096 if (CCC.WantTypeSpecifiers) {
5097 // Add type-specifier keywords to the set of results.
5098 static const char *const CTypeSpecs[] = {
5099 "char", "const", "double", "enum", "float", "int", "long", "short",
5100 "signed", "struct", "union", "unsigned", "void", "volatile",
5101 "_Complex", "_Imaginary",
5102 // storage-specifiers as well
5103 "extern", "inline", "static", "typedef"
5104 };
5105
5106 for (const auto *CTS : CTypeSpecs)
5107 Consumer.addKeywordResult(CTS);
5108
5109 if (SemaRef.getLangOpts().C99)
5110 Consumer.addKeywordResult("restrict");
5111 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
5112 Consumer.addKeywordResult("bool");
5113 else if (SemaRef.getLangOpts().C99)
5114 Consumer.addKeywordResult("_Bool");
5115
5116 if (SemaRef.getLangOpts().CPlusPlus) {
5117 Consumer.addKeywordResult("class");
5118 Consumer.addKeywordResult("typename");
5119 Consumer.addKeywordResult("wchar_t");
5120
5121 if (SemaRef.getLangOpts().CPlusPlus11) {
5122 Consumer.addKeywordResult("char16_t");
5123 Consumer.addKeywordResult("char32_t");
5124 Consumer.addKeywordResult("constexpr");
5125 Consumer.addKeywordResult("decltype");
5126 Consumer.addKeywordResult("thread_local");
5127 }
5128 }
5129
5130 if (SemaRef.getLangOpts().GNUKeywords)
5131 Consumer.addKeywordResult("typeof");
5132 } else if (CCC.WantFunctionLikeCasts) {
5133 static const char *const CastableTypeSpecs[] = {
5134 "char", "double", "float", "int", "long", "short",
5135 "signed", "unsigned", "void"
5136 };
5137 for (auto *kw : CastableTypeSpecs)
5138 Consumer.addKeywordResult(kw);
5139 }
5140
5141 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
5142 Consumer.addKeywordResult("const_cast");
5143 Consumer.addKeywordResult("dynamic_cast");
5144 Consumer.addKeywordResult("reinterpret_cast");
5145 Consumer.addKeywordResult("static_cast");
5146 }
5147
5148 if (CCC.WantExpressionKeywords) {
5149 Consumer.addKeywordResult("sizeof");
5150 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
5151 Consumer.addKeywordResult("false");
5152 Consumer.addKeywordResult("true");
5153 }
5154
5155 if (SemaRef.getLangOpts().CPlusPlus) {
5156 static const char *const CXXExprs[] = {
5157 "delete", "new", "operator", "throw", "typeid"
5158 };
5159 for (const auto *CE : CXXExprs)
5160 Consumer.addKeywordResult(CE);
5161
5162 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
5163 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
5164 Consumer.addKeywordResult("this");
5165
5166 if (SemaRef.getLangOpts().CPlusPlus11) {
5167 Consumer.addKeywordResult("alignof");
5168 Consumer.addKeywordResult("nullptr");
5169 }
5170 }
5171
5172 if (SemaRef.getLangOpts().C11) {
5173 // FIXME: We should not suggest _Alignof if the alignof macro
5174 // is present.
5175 Consumer.addKeywordResult("_Alignof");
5176 }
5177 }
5178
5179 if (CCC.WantRemainingKeywords) {
5180 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
5181 // Statements.
5182 static const char *const CStmts[] = {
5183 "do", "else", "for", "goto", "if", "return", "switch", "while" };
5184 for (const auto *CS : CStmts)
5185 Consumer.addKeywordResult(CS);
5186
5187 if (SemaRef.getLangOpts().CPlusPlus) {
5188 Consumer.addKeywordResult("catch");
5189 Consumer.addKeywordResult("try");
5190 }
5191
5192 if (S && S->getBreakParent())
5193 Consumer.addKeywordResult("break");
5194
5195 if (S && S->getContinueParent())
5196 Consumer.addKeywordResult("continue");
5197
5198 if (SemaRef.getCurFunction() &&
5199 !SemaRef.getCurFunction()->SwitchStack.empty()) {
5200 Consumer.addKeywordResult("case");
5201 Consumer.addKeywordResult("default");
5202 }
5203 } else {
5204 if (SemaRef.getLangOpts().CPlusPlus) {
5205 Consumer.addKeywordResult("namespace");
5206 Consumer.addKeywordResult("template");
5207 }
5208
5209 if (S && S->isClassScope()) {
5210 Consumer.addKeywordResult("explicit");
5211 Consumer.addKeywordResult("friend");
5212 Consumer.addKeywordResult("mutable");
5213 Consumer.addKeywordResult("private");
5214 Consumer.addKeywordResult("protected");
5215 Consumer.addKeywordResult("public");
5216 Consumer.addKeywordResult("virtual");
5217 }
5218 }
5219
5220 if (SemaRef.getLangOpts().CPlusPlus) {
5221 Consumer.addKeywordResult("using");
5222
5223 if (SemaRef.getLangOpts().CPlusPlus11)
5224 Consumer.addKeywordResult("static_assert");
5225 }
5226 }
5227}
5228
5229std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5230 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5232 DeclContext *MemberContext, bool EnteringContext,
5233 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
5234
5235 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
5237 return nullptr;
5238
5239 // In Microsoft mode, don't perform typo correction in a template member
5240 // function dependent context because it interferes with the "lookup into
5241 // dependent bases of class templates" feature.
5242 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
5243 isa<CXXMethodDecl>(CurContext))
5244 return nullptr;
5245
5246 // We only attempt to correct typos for identifiers.
5247 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5248 if (!Typo)
5249 return nullptr;
5250
5251 // If the scope specifier itself was invalid, don't try to correct
5252 // typos.
5253 if (SS && SS->isInvalid())
5254 return nullptr;
5255
5256 // Never try to correct typos during any kind of code synthesis.
5257 if (!CodeSynthesisContexts.empty())
5258 return nullptr;
5259
5260 // Don't try to correct 'super'.
5261 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
5262 return nullptr;
5263
5264 // Abort if typo correction already failed for this specific typo.
5265 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
5266 if (locs != TypoCorrectionFailures.end() &&
5267 locs->second.count(TypoName.getLoc()))
5268 return nullptr;
5269
5270 // Don't try to correct the identifier "vector" when in AltiVec mode.
5271 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5272 // remove this workaround.
5273 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
5274 return nullptr;
5275
5276 // Provide a stop gap for files that are just seriously broken. Trying
5277 // to correct all typos can turn into a HUGE performance penalty, causing
5278 // some files to take minutes to get rejected by the parser.
5279 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
5280 if (Limit && TyposCorrected >= Limit)
5281 return nullptr;
5283
5284 // If we're handling a missing symbol error, using modules, and the
5285 // special search all modules option is used, look for a missing import.
5286 if (ErrorRecovery && getLangOpts().Modules &&
5287 getLangOpts().ModulesSearchAll) {
5288 // The following has the side effect of loading the missing module.
5289 getModuleLoader().lookupMissingImports(Typo->getName(),
5290 TypoName.getBeginLoc());
5291 }
5292
5293 // Extend the lifetime of the callback. We delayed this until here
5294 // to avoid allocations in the hot path (which is where no typo correction
5295 // occurs). Note that CorrectionCandidateCallback is polymorphic and
5296 // initially stack-allocated.
5297 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
5298 auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5299 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
5300 EnteringContext);
5301
5302 // Perform name lookup to find visible, similarly-named entities.
5303 bool IsUnqualifiedLookup = false;
5304 DeclContext *QualifiedDC = MemberContext;
5305 if (MemberContext) {
5306 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
5307
5308 // Look in qualified interfaces.
5309 if (OPT) {
5310 for (auto *I : OPT->quals())
5311 LookupVisibleDecls(I, LookupKind, *Consumer);
5312 }
5313 } else if (SS && SS->isSet()) {
5314 QualifiedDC = computeDeclContext(*SS, EnteringContext);
5315 if (!QualifiedDC)
5316 return nullptr;
5317
5318 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
5319 } else {
5320 IsUnqualifiedLookup = true;
5321 }
5322
5323 // Determine whether we are going to search in the various namespaces for
5324 // corrections.
5325 bool SearchNamespaces
5326 = getLangOpts().CPlusPlus &&
5327 (IsUnqualifiedLookup || (SS && SS->isSet()));
5328
5329 if (IsUnqualifiedLookup || SearchNamespaces) {
5330 // For unqualified lookup, look through all of the names that we have
5331 // seen in this translation unit.
5332 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5333 for (const auto &I : Context.Idents)
5334 Consumer->FoundName(I.getKey());
5335
5336 // Walk through identifiers in external identifier sources.
5337 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5340 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5341 do {
5342 StringRef Name = Iter->Next();
5343 if (Name.empty())
5344 break;
5345
5346 Consumer->FoundName(Name);
5347 } while (true);
5348 }
5349 }
5350
5352 *Consumer->getCorrectionValidator(),
5353 SS && SS->isNotEmpty());
5354
5355 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5356 // to search those namespaces.
5357 if (SearchNamespaces) {
5358 // Load any externally-known namespaces.
5359 if (ExternalSource && !LoadedExternalKnownNamespaces) {
5360 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
5361 LoadedExternalKnownNamespaces = true;
5362 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
5363 for (auto *N : ExternalKnownNamespaces)
5364 KnownNamespaces[N] = true;
5365 }
5366
5367 Consumer->addNamespaces(KnownNamespaces);
5368 }
5369
5370 return Consumer;
5371}
5372
5373/// Try to "correct" a typo in the source code by finding
5374/// visible declarations whose names are similar to the name that was
5375/// present in the source code.
5376///
5377/// \param TypoName the \c DeclarationNameInfo structure that contains
5378/// the name that was present in the source code along with its location.
5379///
5380/// \param LookupKind the name-lookup criteria used to search for the name.
5381///
5382/// \param S the scope in which name lookup occurs.
5383///
5384/// \param SS the nested-name-specifier that precedes the name we're
5385/// looking for, if present.
5386///
5387/// \param CCC A CorrectionCandidateCallback object that provides further
5388/// validation of typo correction candidates. It also provides flags for
5389/// determining the set of keywords permitted.
5390///
5391/// \param MemberContext if non-NULL, the context in which to look for
5392/// a member access expression.
5393///
5394/// \param EnteringContext whether we're entering the context described by
5395/// the nested-name-specifier SS.
5396///
5397/// \param OPT when non-NULL, the search for visible declarations will
5398/// also walk the protocols in the qualified interfaces of \p OPT.
5399///
5400/// \returns a \c TypoCorrection containing the corrected name if the typo
5401/// along with information such as the \c NamedDecl where the corrected name
5402/// was declared, and any additional \c NestedNameSpecifier needed to access
5403/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
5405 Sema::LookupNameKind LookupKind,
5406 Scope *S, CXXScopeSpec *SS,
5408 CorrectTypoKind Mode,
5409 DeclContext *MemberContext,
5410 bool EnteringContext,
5411 const ObjCObjectPointerType *OPT,
5412 bool RecordFailure) {
5413 // Always let the ExternalSource have the first chance at correction, even
5414 // if we would otherwise have given up.
5415 if (ExternalSource) {
5416 if (TypoCorrection Correction =
5417 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
5418 MemberContext, EnteringContext, OPT))
5419 return Correction;
5420 }
5421
5422 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5423 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5424 // some instances of CTC_Unknown, while WantRemainingKeywords is true
5425 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5426 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
5427
5428 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5429 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5430 MemberContext, EnteringContext,
5431 OPT, Mode == CTK_ErrorRecovery);
5432
5433 if (!Consumer)
5434 return TypoCorrection();
5435
5436 // If we haven't found anything, we're done.
5437 if (Consumer->empty())
5438 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5439
5440 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5441 // is not more that about a third of the length of the typo's identifier.
5442 unsigned ED = Consumer->getBestEditDistance(true);
5443 unsigned TypoLen = Typo->getName().size();
5444 if (ED > 0 && TypoLen / ED < 3)
5445 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5446
5447 TypoCorrection BestTC = Consumer->getNextCorrection();
5448 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5449 if (!BestTC)
5450 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5451
5452 ED = BestTC.getEditDistance();
5453
5454 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5455 // If this was an unqualified lookup and we believe the callback
5456 // object wouldn't have filtered out possible corrections, note
5457 // that no correction was found.
5458 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5459 }
5460
5461 // If only a single name remains, return that result.
5462 if (!SecondBestTC ||
5463 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
5464 const TypoCorrection &Result = BestTC;
5465
5466 // Don't correct to a keyword that's the same as the typo; the keyword
5467 // wasn't actually in scope.
5468 if (ED == 0 && Result.isKeyword())
5469 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5470
5472 TC.setCorrectionRange(SS, TypoName);
5473 checkCorrectionVisibility(*this, TC);
5474 return TC;
5475 } else if (SecondBestTC && ObjCMessageReceiver) {
5476 // Prefer 'super' when we're completing in a message-receiver
5477 // context.
5478
5479 if (BestTC.getCorrection().getAsString() != "super") {
5480 if (SecondBestTC.getCorrection().getAsString() == "super")
5481 BestTC = SecondBestTC;
5482 else if ((*Consumer)["super"].front().isKeyword())
5483 BestTC = (*Consumer)["super"].front();
5484 }
5485 // Don't correct to a keyword that's the same as the typo; the keyword
5486 // wasn't actually in scope.
5487 if (BestTC.getEditDistance() == 0 ||
5488 BestTC.getCorrection().getAsString() != "super")
5489 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5490
5491 BestTC.setCorrectionRange(SS, TypoName);
5492 return BestTC;
5493 }
5494
5495 // Record the failure's location if needed and return an empty correction. If
5496 // this was an unqualified lookup and we believe the callback object did not
5497 // filter out possible corrections, also cache the failure for the typo.
5498 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
5499}
5500
5501/// Try to "correct" a typo in the source code by finding
5502/// visible declarations whose names are similar to the name that was
5503/// present in the source code.
5504///
5505/// \param TypoName the \c DeclarationNameInfo structure that contains
5506/// the name that was present in the source code along with its location.
5507///
5508/// \param LookupKind the name-lookup criteria used to search for the name.
5509///
5510/// \param S the scope in which name lookup occurs.
5511///
5512/// \param SS the nested-name-specifier that precedes the name we're
5513/// looking for, if present.
5514///
5515/// \param CCC A CorrectionCandidateCallback object that provides further
5516/// validation of typo correction candidates. It also provides flags for
5517/// determining the set of keywords permitted.
5518///
5519/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
5520/// diagnostics when the actual typo correction is attempted.
5521///
5522/// \param TRC A TypoRecoveryCallback functor that will be used to build an
5523/// Expr from a typo correction candidate.
5524///
5525/// \param MemberContext if non-NULL, the context in which to look for
5526/// a member access expression.
5527///
5528/// \param EnteringContext whether we're entering the context described by
5529/// the nested-name-specifier SS.
5530///
5531/// \param OPT when non-NULL, the search for visible declarations will
5532/// also walk the protocols in the qualified interfaces of \p OPT.
5533///
5534/// \returns a new \c TypoExpr that will later be replaced in the AST with an
5535/// Expr representing the result of performing typo correction, or nullptr if
5536/// typo correction is not possible. If nullptr is returned, no diagnostics will
5537/// be emitted and it is the responsibility of the caller to emit any that are
5538/// needed.
5540 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5543 DeclContext *MemberContext, bool EnteringContext,
5544 const ObjCObjectPointerType *OPT) {
5545 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5546 MemberContext, EnteringContext,
5547 OPT, Mode == CTK_ErrorRecovery);
5548
5549 // Give the external sema source a chance to correct the typo.
5550 TypoCorrection ExternalTypo;
5551 if (ExternalSource && Consumer) {
5552 ExternalTypo = ExternalSource->CorrectTypo(
5553 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
5554 MemberContext, EnteringContext, OPT);
5555 if (ExternalTypo)
5556 Consumer->addCorrection(ExternalTypo);
5557 }
5558
5559 if (!Consumer || Consumer->empty())
5560 return nullptr;
5561
5562 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5563 // is not more that about a third of the length of the typo's identifier.
5564 unsigned ED = Consumer->getBestEditDistance(true);
5565 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5566 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
5567 return nullptr;
5568 ExprEvalContexts.back().NumTypos++;
5569 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),
5570 TypoName.getLoc());
5571}
5572
5574 if (!CDecl) return;
5575
5576 if (isKeyword())
5577 CorrectionDecls.clear();
5578
5579 CorrectionDecls.push_back(CDecl);
5580
5581 if (!CorrectionName)
5582 CorrectionName = CDecl->getDeclName();
5583}
5584
5585std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5586 if (CorrectionNameSpec) {
5587 std::string tmpBuffer;
5588 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5589 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
5590 PrefixOStream << CorrectionName;
5591 return PrefixOStream.str();
5592 }
5593
5594 return CorrectionName.getAsString();
5595}
5596
5598 const TypoCorrection &candidate) {
5599 if (!candidate.isResolved())
5600 return true;
5601
5602 if (candidate.isKeyword())
5605
5606 bool HasNonType = false;
5607 bool HasStaticMethod = false;
5608 bool HasNonStaticMethod = false;
5609 for (Decl *D : candidate) {
5610 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5611 D = FTD->getTemplatedDecl();
5612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5613 if (Method->isStatic())
5614 HasStaticMethod = true;
5615 else
5616 HasNonStaticMethod = true;
5617 }
5618 if (!isa<TypeDecl>(D))
5619 HasNonType = true;
5620 }
5621
5622 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5623 !candidate.getCorrectionSpecifier())
5624 return false;
5625
5626 return WantTypeSpecifiers || HasNonType;
5627}
5628
5630 bool HasExplicitTemplateArgs,
5631 MemberExpr *ME)
5632 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5633 CurContext(SemaRef.CurContext), MemberFn(ME) {
5634 WantTypeSpecifiers = false;
5635 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5636 !HasExplicitTemplateArgs && NumArgs == 1;
5637 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5638 WantRemainingKeywords = false;
5639}
5640
5642 if (!candidate.getCorrectionDecl())
5643 return candidate.isKeyword();
5644
5645 for (auto *C : candidate) {
5646 FunctionDecl *FD = nullptr;
5647 NamedDecl *ND = C->getUnderlyingDecl();
5648 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5649 FD = FTD->getTemplatedDecl();
5650 if (!HasExplicitTemplateArgs && !FD) {
5651 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5652 // If the Decl is neither a function nor a template function,
5653 // determine if it is a pointer or reference to a function. If so,
5654 // check against the number of arguments expected for the pointee.
5655 QualType ValType = cast<ValueDecl>(ND)->getType();
5656 if (ValType.isNull())
5657 continue;
5658 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5659 ValType = ValType->getPointeeType();
5660 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5661 if (FPT->getNumParams() == NumArgs)
5662 return true;
5663 }
5664 }
5665
5666 // A typo for a function-style cast can look like a function call in C++.
5667 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5668 : isa<TypeDecl>(ND)) &&
5669 CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5670 // Only a class or class template can take two or more arguments.
5671 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5672
5673 // Skip the current candidate if it is not a FunctionDecl or does not accept
5674 // the current number of arguments.
5675 if (!FD || !(FD->getNumParams() >= NumArgs &&
5676 FD->getMinRequiredArguments() <= NumArgs))
5677 continue;
5678
5679 // If the current candidate is a non-static C++ method, skip the candidate
5680 // unless the method being corrected--or the current DeclContext, if the
5681 // function being corrected is not a method--is a method in the same class
5682 // or a descendent class of the candidate's parent class.
5683 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
5684 if (MemberFn || !MD->isStatic()) {
5685 const auto *CurMD =
5686 MemberFn
5687 ? dyn_cast_if_present<CXXMethodDecl>(MemberFn->getMemberDecl())
5688 : dyn_cast_if_present<CXXMethodDecl>(CurContext);
5689 const CXXRecordDecl *CurRD =
5690 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5691 const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5692 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5693 continue;
5694 }
5695 }
5696 return true;
5697 }
5698 return false;
5699}
5700
5701void Sema::diagnoseTypo(const TypoCorrection &Correction,
5702 const PartialDiagnostic &TypoDiag,
5703 bool ErrorRecovery) {
5704 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5705 ErrorRecovery);
5706}
5707
5708/// Find which declaration we should import to provide the definition of
5709/// the given declaration.
5711 if (const auto *VD = dyn_cast<VarDecl>(D))
5712 return VD->getDefinition();
5713 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5714 return FD->getDefinition();
5715 if (const auto *TD = dyn_cast<TagDecl>(D))
5716 return TD->getDefinition();
5717 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))
5718 return ID->getDefinition();
5719 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D))
5720 return PD->getDefinition();
5721 if (const auto *TD = dyn_cast<TemplateDecl>(D))
5722 if (const NamedDecl *TTD = TD->getTemplatedDecl())
5723 return getDefinitionToImport(TTD);
5724 return nullptr;
5725}
5726
5728 MissingImportKind MIK, bool Recover) {
5729 // Suggest importing a module providing the definition of this entity, if
5730 // possible.
5731 const NamedDecl *Def = getDefinitionToImport(Decl);
5732 if (!Def)
5733 Def = Decl;
5734
5735 Module *Owner = getOwningModule(Def);
5736 assert(Owner && "definition of hidden declaration is not in a module");
5737
5738 llvm::SmallVector<Module*, 8> OwningModules;
5739 OwningModules.push_back(Owner);
5740 auto Merged = Context.getModulesWithMergedDefinition(Def);
5741 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5742
5743 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5744 Recover);
5745}
5746
5747/// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5748/// suggesting the addition of a #include of the specified file.
5750 llvm::StringRef IncludingFile) {
5751 bool IsAngled = false;
5753 E, IncludingFile, &IsAngled);
5754 return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"');
5755}
5756
5758 SourceLocation DeclLoc,
5759 ArrayRef<Module *> Modules,
5760 MissingImportKind MIK, bool Recover) {
5761 assert(!Modules.empty());
5762
5763 // See https://github.com/llvm/llvm-project/issues/73893. It is generally
5764 // confusing than helpful to show the namespace is not visible.
5765 if (isa<NamespaceDecl>(Decl))
5766 return;
5767
5768 auto NotePrevious = [&] {
5769 // FIXME: Suppress the note backtrace even under
5770 // -fdiagnostics-show-note-include-stack. We don't care how this
5771 // declaration was previously reached.
5772 Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
5773 };
5774
5775 // Weed out duplicates from module list.
5776 llvm::SmallVector<Module*, 8> UniqueModules;
5777 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5778 for (auto *M : Modules) {
5779 if (M->isExplicitGlobalModule() || M->isPrivateModule())
5780 continue;
5781 if (UniqueModuleSet.insert(M).second)
5782 UniqueModules.push_back(M);
5783 }
5784
5785 // Try to find a suitable header-name to #include.
5786 std::string HeaderName;
5787 if (OptionalFileEntryRef Header =
5788 PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5789 if (const FileEntry *FE =
5791 HeaderName =
5792 getHeaderNameForHeader(PP, *Header, FE->tryGetRealPathName());
5793 }
5794
5795 // If we have a #include we should suggest, or if all definition locations
5796 // were in global module fragments, don't suggest an import.
5797 if (!HeaderName.empty() || UniqueModules.empty()) {
5798 // FIXME: Find a smart place to suggest inserting a #include, and add
5799 // a FixItHint there.
5800 Diag(UseLoc, diag::err_module_unimported_use_header)
5801 << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5802 // Produce a note showing where the entity was declared.
5803 NotePrevious();
5804 if (Recover)
5806 return;
5807 }
5808
5809 Modules = UniqueModules;
5810
5811 auto GetModuleNameForDiagnostic = [this](const Module *M) -> std::string {
5812 if (M->isModuleMapModule())
5813 return M->getFullModuleName();
5814
5815 Module *CurrentModule = getCurrentModule();
5816
5817 if (M->isImplicitGlobalModule())
5818 M = M->getTopLevelModule();
5819
5820 bool IsInTheSameModule =
5821 CurrentModule && CurrentModule->getPrimaryModuleInterfaceName() ==
5823
5824 // If the current module unit is in the same module with M, it is OK to show
5825 // the partition name. Otherwise, it'll be sufficient to show the primary
5826 // module name.
5827 if (IsInTheSameModule)
5828 return M->getTopLevelModuleName().str();
5829 else
5830 return M->getPrimaryModuleInterfaceName().str();
5831 };
5832
5833 if (Modules.size() > 1) {
5834 std::string ModuleList;
5835 unsigned N = 0;
5836 for (const auto *M : Modules) {
5837 ModuleList += "\n ";
5838 if (++N == 5 && N != Modules.size()) {
5839 ModuleList += "[...]";
5840 break;
5841 }
5842 ModuleList += GetModuleNameForDiagnostic(M);
5843 }
5844
5845 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5846 << (int)MIK << Decl << ModuleList;
5847 } else {
5848 // FIXME: Add a FixItHint that imports the corresponding module.
5849 Diag(UseLoc, diag::err_module_unimported_use)
5850 << (int)MIK << Decl << GetModuleNameForDiagnostic(Modules[0]);
5851 }
5852
5853 NotePrevious();
5854
5855 // Try to recover by implicitly importing this module.
5856 if (Recover)
5858}
5859
5860/// Diagnose a successfully-corrected typo. Separated from the correction
5861/// itself to allow external validation of the result, etc.
5862///
5863/// \param Correction The result of performing typo correction.
5864/// \param TypoDiag The diagnostic to produce. This will have the corrected
5865/// string added to it (and usually also a fixit).
5866/// \param PrevNote A note to use when indicating the location of the entity to
5867/// which we are correcting. Will have the correction string added to it.
5868/// \param ErrorRecovery If \c true (the default), the caller is going to
5869/// recover from the typo as if the corrected string had been typed.
5870/// In this case, \c PDiag must be an error, and we will attach a fixit
5871/// to it.
5872void Sema::diagnoseTypo(const TypoCorrection &Correction,
5873 const PartialDiagnostic &TypoDiag,
5874 const PartialDiagnostic &PrevNote,
5875 bool ErrorRecovery) {
5876 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5877 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5879 Correction.getCorrectionRange(), CorrectedStr);
5880
5881 // Maybe we're just missing a module import.
5882 if (Correction.requiresImport()) {
5883 NamedDecl *Decl = Correction.getFoundDecl();
5884 assert(Decl && "import required but no declaration to import");
5885
5887 MissingImportKind::Declaration, ErrorRecovery);
5888 return;
5889 }
5890
5891 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5892 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5893
5894 NamedDecl *ChosenDecl =
5895 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5896 if (PrevNote.getDiagID() && ChosenDecl)
5897 Diag(ChosenDecl->getLocation(), PrevNote)
5898 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5899
5900 // Add any extra diagnostics.
5901 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5902 Diag(Correction.getCorrectionRange().getBegin(), PD);
5903}
5904
5905TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5906 TypoDiagnosticGenerator TDG,
5907 TypoRecoveryCallback TRC,
5908 SourceLocation TypoLoc) {
5909 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5910 auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);
5911 auto &State = DelayedTypos[TE];
5912 State.Consumer = std::move(TCC);
5913 State.DiagHandler = std::move(TDG);
5914 State.RecoveryHandler = std::move(TRC);
5915 if (TE)
5916 TypoExprs.push_back(TE);
5917 return TE;
5918}
5919
5921 auto Entry = DelayedTypos.find(TE);
5922 assert(Entry != DelayedTypos.end() &&
5923 "Failed to get the state for a TypoExpr!");
5924 return Entry->second;
5925}
5926
5928 DelayedTypos.erase(TE);
5929}
5930
5932 DeclarationNameInfo Name(II, IILoc);
5933 LookupResult R(*this, Name, LookupAnyName,
5934 RedeclarationKind::NotForRedeclaration);
5936 R.setHideTags(false);
5937 LookupName(R, S);
5938 R.dump();
5939}
5940
5942 E->dump();
5943}
5944
5946 // A declaration with an owning module for linkage can never link against
5947 // anything that is not visible. We don't need to check linkage here; if
5948 // the context has internal linkage, redeclaration lookup won't find things
5949 // from other TUs, and we can't safely compute linkage yet in general.
5950 if (cast<Decl>(CurContext)->getOwningModuleForLinkage(/*IgnoreLinkage*/ true))
5951 return RedeclarationKind::ForVisibleRedeclaration;
5952 return RedeclarationKind::ForExternalRedeclaration;
5953}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
StringRef P
#define SM(sm)
Definition: Cuda.cpp:83
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
int Category
Definition: Format.cpp:2978
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:146
unsigned Iter
Definition: HTMLLogger.cpp:154
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Redeclaration.h:18
static Module * getDefiningModule(Sema &S, Decl *Entity)
Find the module in which the given declaration was defined.
static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind, const NamedDecl *D, const NamedDecl *Existing)
Determine whether D is a better lookup result than Existing, given that they declare the same entity.
Definition: SemaLookup.cpp:370
static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class)
Determine whether we can declare a special member function within the class at this point.
Definition: SemaLookup.cpp:999
static bool canHideTag(const NamedDecl *D)
Determine whether D can hide a tag declaration.
Definition: SemaLookup.cpp:464
static std::string getHeaderNameForHeader(Preprocessor &PP, FileEntryRef E, llvm::StringRef IncludingFile)
Get a "quoted.h" or <angled.h> include path to use in a diagnostic suggesting the addition of a #incl...
static void addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T)
static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name)
Lookup an OpenCL typedef type.
Definition: SemaLookup.cpp:719
static DeclContext * findOuterContext(Scope *S)
Find the outer declaration context from this scope.
static void LookupPotentialTypoResult(Sema &SemaRef, LookupResult &Res, IdentifierInfo *Name, Scope *S, CXXScopeSpec *SS, DeclContext *MemberContext, bool EnteringContext, bool isObjCIvarLookup, bool FindHidden)
Perform name lookup for a possible result for typo correction.
static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC)
Check whether the declarations found for a typo correction are visible.
static bool isNamespaceOrTranslationUnitScope(Scope *S)
static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, DeclContext *StartDC)
Perform qualified name lookup in the namespaces nominated by using directives by the given context.
static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC)
static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name)
Lookup an OpenCL enum type.
Definition: SemaLookup.cpp:706
static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, DeclContext *Ctx)
static bool hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name)
Determine whether this is the name of an implicitly-declared special member function.
static void DeclareImplicitMemberFunctionsWithName(Sema &S, DeclarationName Name, SourceLocation Loc, const DeclContext *DC)
If there are any implicit member functions with the given name that need to be declared in the given ...
static void AddKeywordsToConsumer(Sema &SemaRef, TypoCorrectionConsumer &Consumer, Scope *S, CorrectionCandidateCallback &CCC, bool AfterNestedNameSpecifier)
Add keywords to the consumer as possible typo corrections.
static void GetQualTypesForOpenCLBuiltin(Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt, SmallVector< QualType, 1 > &RetTypes, SmallVector< SmallVector< QualType, 1 >, 5 > &ArgTypes)
Get the QualType instances of the return type and arguments for an OpenCL builtin function signature.
Definition: SemaLookup.cpp:742
static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass, llvm::StringRef Name)
Diagnose a missing builtin type.
Definition: SemaLookup.cpp:698
static bool hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
static bool hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Filter F, Sema::AcceptableKind Kind)
static bool isCandidateViable(CorrectionCandidateCallback &CCC, TypoCorrection &Candidate)
static const DeclContext * getContextForScopeMatching(const Decl *D)
Get a representative context for a declaration such that two declarations will have the same context ...
Definition: SemaLookup.cpp:355
static NamedDecl * findAcceptableDecl(Sema &SemaRef, NamedDecl *D, unsigned IDNS)
Retrieve the visible declaration corresponding to D, if any.
static void GetOpenCLBuiltinFctOverloads(ASTContext &Context, unsigned GenTypeMaxCnt, std::vector< QualType > &FunctionList, SmallVector< QualType, 1 > &RetTypes, SmallVector< SmallVector< QualType, 1 >, 5 > &ArgTypes)
Create a list of the candidate function overloads for an OpenCL builtin function.
Definition: SemaLookup.cpp:771
static const unsigned MaxTypoDistanceResultSets
static const NamedDecl * getDefinitionToImport(const NamedDecl *D)
Find which declaration we should import to provide the definition of the given declaration.
static void getNestedNameSpecifierIdentifiers(NestedNameSpecifier *NNS, SmallVectorImpl< const IdentifierInfo * > &Identifiers)
static bool hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
static unsigned getIDNS(Sema::LookupNameKind NameKind, bool CPlusPlus, bool Redeclaration)
Definition: SemaLookup.cpp:213
static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR, IdentifierInfo *II, const unsigned FctIndex, const unsigned Len)
When trying to resolve a function name, if isOpenCLBuiltin() returns a non-null <Index,...
Definition: SemaLookup.cpp:816
static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S)
Looks up the declaration of "struct objc_super" and saves it for later use in building builtin declar...
Definition: SemaLookup.cpp:982
static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, const DeclContext *NS, UnqualUsingDirectiveSet &UDirs)
SourceLocation Loc
Definition: SemaObjC.cpp:755
const NestedNameSpecifier * Specifier
__DEVICE__ long long abs(long long __n)
__device__ int
A class for storing results from argument-dependent lookup.
Definition: Lookup.h:869
void insert(NamedDecl *D)
Adds a new ADL candidate to this map.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
const SmallVectorImpl< Type * > & getTypes() const
Definition: ASTContext.h:1207
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getRecordType(const RecordDecl *Decl) const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2575
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getEnumType(const EnumDecl *Decl) const
CanQualType DependentTy
Definition: ASTContext.h:1119
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1591
IdentifierTable & Idents
Definition: ASTContext.h:644
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
void setObjCSuperType(QualType ST)
Definition: ASTContext.h:1836
CanQualType OverloadTy
Definition: ASTContext.h:1119
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2618
CanQualType VoidTy
Definition: ASTContext.h:1091
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1569
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:160
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
std::list< CXXBasePath >::iterator paths_iterator
std::list< CXXBasePath >::const_iterator const_paths_iterator
void swap(CXXBasePaths &Other)
Swap this data structure's contents with another CXXBasePaths object.
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
base_class_iterator bases_end()
Definition: DeclCXX.h:628
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:569
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition: DeclCXX.h:777
bool needsImplicitMoveConstructor() const
Determine whether this class should get an implicit move constructor or if any existing special membe...
Definition: DeclCXX.h:896
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1723
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1930
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition: DeclCXX.h:626
bool needsImplicitCopyConstructor() const
Determine whether this class needs an implicit copy constructor to be lazily declared.
Definition: DeclCXX.h:810
bool needsImplicitDestructor() const
Determine whether this class needs an implicit destructor to be lazily declared.
Definition: DeclCXX.h:1011
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1975
bool needsImplicitMoveAssignment() const
Determine whether this class should get an implicit move assignment operator or if any existing speci...
Definition: DeclCXX.h:987
bool needsImplicitCopyAssignment() const
Determine whether this class needs an implicit copy assignment operator to be lazily declared.
Definition: DeclCXX.h:929
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
SourceRange getRange() const
Definition: DeclSpec.h:80
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
Declaration of a class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
virtual unsigned RankCandidate(const TypoCorrection &candidate)
Method used by Sema::CorrectTypo to assign an "edit distance" rank to a candidate (where a lower valu...
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
virtual std::unique_ptr< CorrectionCandidateCallback > clone()=0
Clone this CorrectionCandidateCallback.
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
DeclListNode::iterator iterator
Definition: DeclBase.h:1379
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
Definition: DeclBase.cpp:2090
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1316
ASTContext & getParentASTContext() const
Definition: DeclBase.h:2095
lookups_range noload_lookups(bool PreserveInternalState) const
Definition: DeclLookups.h:89
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
bool isTranslationUnit() const
Definition: DeclBase.h:2142
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
lookups_range lookups() const
Definition: DeclLookups.h:75
bool shouldUseQualifiedLookup() const
Definition: DeclBase.h:2672
void setUseQualifiedLookup(bool use=true) const
Definition: DeclBase.h:2668
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1372
bool isInlineNamespace() const
Definition: DeclBase.cpp:1261
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1233
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1352
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:235
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1109
void addAttr(Attr *A)
Definition: DeclBase.cpp:991
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:849
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:883
bool isInvisibleOutsideTheOwningModule() const
Definition: DeclBase.h:666
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1090
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Definition: DeclBase.cpp:1099
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:833
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
void dump() const
Definition: ASTDumper.cpp:220
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2739
bool isInvalidDecl() const
Definition: DeclBase.h:594
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:879
SourceLocation getLocation() const
Definition: DeclBase.h:445
@ IDNS_NonMemberOperator
This declaration is a C++ operator declared in a non-class context.
Definition: DeclBase.h:168
@ IDNS_TagFriend
This declaration is a friend class.
Definition: DeclBase.h:157
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
@ IDNS_Type
Types, declared with 'struct foo', typedefs, etc.
Definition: DeclBase.h:130
@ IDNS_OMPReduction
This declaration is an OpenMP user defined reduction construction.
Definition: DeclBase.h:178
@ IDNS_Label
Labels, declared with 'x:' and referenced with 'goto x'.
Definition: DeclBase.h:117
@ IDNS_Member
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:136
@ IDNS_OMPMapper
This declaration is an OpenMP user defined mapper.
Definition: DeclBase.h:181
@ IDNS_ObjCProtocol
Objective C @protocol.
Definition: DeclBase.h:147
@ IDNS_Namespace
Namespaces, declared with 'namespace foo {}'.
Definition: DeclBase.h:140
@ IDNS_OrdinaryFriend
This declaration is a friend function.
Definition: DeclBase.h:152
@ IDNS_Using
This declaration is a using declaration.
Definition: DeclBase.h:163
@ IDNS_LocalExtern
This declaration is a function-local extern declaration of a variable or function.
Definition: DeclBase.h:175
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:125
bool isDeprecated(std::string *Message=nullptr) const
Determine whether this declaration is marked 'deprecated'.
Definition: DeclBase.h:745
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
void setImplicit(bool I=true)
Definition: DeclBase.h:600
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:939
DeclContext * getDeclContext()
Definition: DeclBase.h:454
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:486
bool hasTagIdentifierNamespace() const
Definition: DeclBase.h:889
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition: DeclBase.cpp:507
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
std::string getAsString() const
Retrieve the human-readable string for this name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:562
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:850
Represents an enum.
Definition: Decl.h:3867
The return type of classify().
Definition: Expr.h:330
This represents one expression.
Definition: Expr.h:110
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
bool isFPConstrained() const
Definition: LangOptions.h:843
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:300
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs, MemberExpr *ME=nullptr)
Represents a function declaration or definition.
Definition: Decl.h:1971
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4113
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2502
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2160
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4900
ArrayRef< QualType > param_types() const
Definition: Type.h:5044
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4482
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
QualType getReturnType() const
Definition: Type.h:4573
std::string suggestPathToFileForDiagnostics(FileEntryRef File, llvm::StringRef MainFile, bool *IsAngled=nullptr) const
Suggest a path by which the specified file could be found, for use in diagnostics to suggest a #inclu...
Provides lookups to, and iteration over, IdentiferInfo objects.
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
iterator end()
Returns the end iterator.
bool isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IdentifierInfoLookup * getExternalIdentifierLookup() const
Retrieve the external identifier lookup object, if any.
Represents the declaration of a label.
Definition: Decl.h:499
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition: Decl.cpp:5339
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void restart()
Restart the iteration.
Definition: Lookup.h:716
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition: Lookup.h:488
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
void setShadowed()
Note that we found and ignored a declaration while performing lookup.
Definition: Lookup.h:514
static bool isAvailableForLookup(Sema &SemaRef, NamedDecl *ND)
Determine whether this lookup is permitted to see the declaration.
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
void setFindLocalExtern(bool FindLocalExtern)
Definition: Lookup.h:753
void setAllowHidden(bool AH)
Specify whether hidden declarations are visible, e.g., for recovery reasons.
Definition: Lookup.h:298
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void setContextRange(SourceRange SR)
Sets a 'context' source range.
Definition: Lookup.h:651
static bool isAcceptable(Sema &SemaRef, NamedDecl *D, Sema::AcceptableKind Kind)
Definition: Lookup.h:376
void setAmbiguousQualifiedTagHiding()
Make these results show that the name was found in different contexts and a tag decl was hidden by an...
Definition: Lookup.h:600
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
bool isTemplateNameLookup() const
Definition: Lookup.h:322
void setAmbiguousBaseSubobjects(CXXBasePaths &P)
Make these results show that the name was found in distinct base classes of the same type.
Definition: SemaLookup.cpp:663
bool isSingleTagDecl() const
Asks if the result is a single tag decl.
Definition: Lookup.h:581
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P)
Make these results show that the name was found in base classes of different types.
Definition: SemaLookup.cpp:671
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
void setHideTags(bool Hide)
Sets whether tag declarations should be hidden by non-tag declarations during resolution.
Definition: Lookup.h:311
bool isAmbiguous() const
Definition: Lookup.h:324
NamedDecl * getAcceptableDecl(NamedDecl *D) const
Retrieve the accepted (re)declaration of the given declaration, if there is one.
Definition: Lookup.h:408
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
unsigned getIdentifierNamespace() const
Returns the identifier namespace mask for this lookup.
Definition: Lookup.h:426
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:670
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition: Lookup.h:457
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void print(raw_ostream &)
Definition: SemaLookup.cpp:679
static bool isReachable(Sema &SemaRef, NamedDecl *D)
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
bool isForRedeclaration() const
True if this lookup is just looking for an existing declaration.
Definition: Lookup.h:280
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:146
@ AmbiguousBaseSubobjectTypes
Name lookup results in an ambiguity because multiple entities that meet the lookup criteria were foun...
Definition: Lookup.h:89
@ AmbiguousReferenceToPlaceholderVariable
Name lookup results in an ambiguity because multiple placeholder variables were found in the same sco...
Definition: Lookup.h:129
@ AmbiguousReference
Name lookup results in an ambiguity because multiple definitions of entity that meet the lookup crite...
Definition: Lookup.h:118
@ AmbiguousBaseSubobjects
Name lookup results in an ambiguity because multiple nonstatic entities that meet the lookup criteria...
Definition: Lookup.h:103
void setNotFoundInCurrentInstantiation()
Note that while no result was found in the current instantiation, there were dependent base classes t...
Definition: Lookup.h:501
static bool isVisible(Sema &SemaRef, NamedDecl *D)
Determine whether the given declaration is visible to the program.
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
QualType getPointeeType() const
Definition: Type.h:3476
const Type * getClass() const
Definition: Type.h:3490
virtual bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc)=0
Check global module index for missing imports.
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:676
bool isPrivateModule() const
Definition: Module.h:210
bool isModuleVisible(const Module *M) const
Determine whether the specified module would be visible to a lookup at the end of this module.
Definition: Module.h:772
bool isModuleInterfaceUnit() const
Definition: Module.h:624
bool isModuleMapModule() const
Definition: Module.h:212
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:592
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition: Module.h:631
bool isExplicitGlobalModule() const
Definition: Module.h:203
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition: Module.h:200
bool isImplicitGlobalModule() const
Definition: Module.h:206
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:666
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:648
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1082
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
NamedDecl * getMostRecentDecl()
Definition: Decl.h:476
bool isExternallyDeclarable() const
Determine whether this declaration can be redeclared in a different translation unit.
Definition: Decl.h:414
Represent a C++ namespace.
Definition: Decl.h:547
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:605
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
void print(raw_ostream &OS, const PrintingPolicy &Policy, bool ResolveTemplateArguments=false) const
Print this nested name specifier to the given output stream.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition: Type.h:7008
qual_range quals() const
Definition: Type.h:7127
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2978
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3038
llvm::iterator_range< decls_iterator > decls() const
Definition: ExprCXX.h:3076
Represents a parameter to a function.
Definition: Decl.h:1761
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2915
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
bool isMacroDefined(StringRef Id)
HeaderSearch & getHeaderSearchInfo() const
OptionalFileEntryRef getHeaderToIncludeForDiagnostics(SourceLocation IncLoc, SourceLocation MLoc)
We want to produce a diagnostic at location IncLoc concerning an unreachable effect at location MLoc ...
A (possibly-)qualified type.
Definition: Type.h:940
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:75
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: Type.h:1159
Represents a struct/union/class.
Definition: Decl.h:4168
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition: Scope.h:274
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:381
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:384
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9410
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9440
SpecialMemberOverloadResult - The overloading result for a special member function.
Definition: Sema.h:7241
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:8970
CXXConstructorDecl * DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit default constructor for the given class.
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:10173
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:10157
llvm::DenseSet< Module * > & getLookupModules()
Get the set of additional modules that should be checked during name lookup.
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:7285
@ LookupLabel
Label name lookup.
Definition: Sema.h:7294
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7289
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition: Sema.h:7316
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:7308
@ LookupOMPReductionName
Look up the name of an OpenMP user-defined reduction operation.
Definition: Sema.h:7330
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:7324
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition: Sema.h:7326
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:7321
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:7301
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:7328
@ LookupNamespaceName
Look up a namespace name within a C++ using directive or namespace alias definition,...
Definition: Sema.h:7312
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7297
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition: Sema.h:7304
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7292
@ LookupOMPMapperName
Look up the name of an OpenMP user-defined mapper.
Definition: Sema.h:7332
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:7334
bool hasReachableDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
MissingImportKind
Kinds of missing import.
Definition: Sema.h:7550
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class)
Force the declaration of any implicitly-declared members of this class.
bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules)
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:992
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class)
Perform qualified name lookup into all base classes of the given class.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
@ AR_accessible
Definition: Sema.h:1075
Preprocessor & getPreprocessor() const
Definition: Sema.h:516
CXXConstructorDecl * DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit move constructor for the given class.
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
IdentifierInfo * getSuperIdentifier() const
Definition: Sema.cpp:2686
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:9070
bool DisableTypoCorrection
Tracks whether we are in a context where typo correction is disabled.
Definition: Sema.h:7223
llvm::DenseMap< NamedDecl *, NamedDecl * > VisibleNamespaceCache
Map from the most recent declaration of a namespace to the most recent visible declaration of that na...
Definition: Sema.h:10177
bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def)
ASTContext & Context
Definition: Sema.h:848
IdentifierSourceLocations TypoCorrectionFailures
A cache containing identifiers for which typo correction failed and their locations,...
Definition: Sema.h:7234
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:514
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:918
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1523
bool DeclareRISCVSiFiveVectorBuiltins
Indicate RISC-V SiFive vector builtin functions enabled or not.
Definition: Sema.h:11719
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:2403
ASTContext & getASTContext() const
Definition: Sema.h:517
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
unsigned TyposCorrected
The number of typos corrected by CorrectTypo.
Definition: Sema.h:7226
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:765
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition: Sema.h:2636
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1504
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
FPOptions & getCurFPFeatures()
Definition: Sema.h:512
CXXConstructorDecl * LookupDefaultConstructor(CXXRecordDecl *Class)
Look up the default constructor for the given class.
const LangOptions & getLangOpts() const
Definition: Sema.h:510
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
TypoExpr * CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope=true, bool LoadExternal=true)
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:847
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:11615
CXXMethodDecl * DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit move assignment operator for the given class.
AcceptableKind
Definition: Sema.h:7277
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1511
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:882
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11609
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:7663
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2322
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
std::function< void(const TypoCorrection &)> TypoDiagnosticGenerator
Definition: Sema.h:7364
CXXMethodDecl * LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the moving assignment operator for the given class.
llvm::SmallVector< TypoExpr *, 2 > TypoExprs
Holds TypoExprs that are created from createDelayedTypo.
Definition: Sema.h:7275
CXXMethodDecl * DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl)
Declare the implicit copy assignment operator for the given class.
CXXConstructorDecl * LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the moving constructor for the given class.
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition: Sema.h:11622
CXXMethodDecl * LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals)
Look up the copying assignment operator for the given class.
bool isModuleVisible(const Module *M, bool ModulePrivate=false)
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
bool hasVisibleMergedDefinition(const NamedDecl *Def)
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
llvm::FoldingSet< SpecialMemberOverloadResultEntry > SpecialMemberCache
A cache of special member function overload resolution results for C++ records.
Definition: Sema.h:7269
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation())
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
CorrectTypoKind
Definition: Sema.h:7527
@ CTK_ErrorRecovery
Definition: Sema.h:7529
RedeclarationKind forRedeclarationInCurContext() const
bool DeclareRISCVVBuiltins
Indicate RISC-V vector builtin functions enabled or not.
Definition: Sema.h:11716
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
ASTConsumer & Consumer
Definition: Sema.h:849
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition: Sema.cpp:69
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:820
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
void DiagnoseAmbiguousLookup(LookupResult &Result)
Produce a diagnostic describing the ambiguity that resulted from name lookup.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6364
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:851
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
std::function< ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback
Definition: Sema.h:7366
DiagnosticsEngine & Diags
Definition: Sema.h:850
CXXConstructorDecl * DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl)
Declare the implicit copy constructor for the given class.
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
bool hasAcceptableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules, Sema::AcceptableKind Kind)
Determine if the template parameter D has a reachable default argument.
AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found)
Checks access to a member.
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition: Sema.h:10168
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:806
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:520
bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, AcceptableKind Kind, bool OnlyNeedComplete=false)
Definition: SemaType.cpp:8860
void clearDelayedTypo(TypoExpr *TE)
Clears the state of the given TypoExpr.
LiteralOperatorLookupResult
The possible outcomes of name lookup for a literal operator.
Definition: Sema.h:7338
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition: Sema.h:7342
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:7348
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:7340
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:7345
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:7356
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:7352
void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II)
Called on #pragma clang __debug dump II.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
IdentifierResolver IdResolver
Definition: Sema.h:2524
const TypoExprState & getTypoExprState(TypoExpr *TE) const
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
CXXDestructorDecl * DeclareImplicitDestructor(CXXRecordDecl *ClassDecl)
Declare the implicit destructor for the given class.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod)
Create an implicit import of the given module at the given source location, for error recovery,...
Definition: SemaModule.cpp:823
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void dump() const
Dumps the specified AST fragment and all subtrees to llvm::errs().
Definition: ASTDumper.cpp:290
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3584
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:4012
A template argument list.
Definition: DeclTemplate.h:244
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6089
Represents a declaration of a type.
Definition: Decl.h:3390
const Type * getTypeForDecl() const
Definition: Decl.h:3414
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2000
QualType getCanonicalTypeInternal() const
Definition: Type.h:2936
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
bool isAnyPointerType() const
Definition: Type.h:7616
TypeClass getTypeClass() const
Definition: Type.h:2300
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3432
void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass) override
Invoked each time Sema::LookupVisibleDecls() finds a declaration visible from the current scope or co...
void addKeywordResult(StringRef Keyword)
void addCorrection(TypoCorrection Correction)
const TypoCorrection & getNextCorrection()
Return the next typo correction that passes all internal filters and is deemed valid by the consumer'...
void FoundName(StringRef Name)
void addNamespaces(const llvm::MapVector< NamespaceDecl *, bool > &KnownNamespaces)
Set-up method to add to the consumer the set of namespaces to use in performing corrections to nested...
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
ArrayRef< PartialDiagnostic > getExtraDiagnostics() const
static const unsigned InvalidDistance
void addCorrectionDecl(NamedDecl *CDecl)
Add the given NamedDecl to the list of NamedDecls that are the declarations associated with the Decla...
void setCorrectionDecls(ArrayRef< NamedDecl * > Decls)
Clears the list of NamedDecls and adds the given set.
std::string getAsString(const LangOptions &LO) const
bool requiresImport() const
Returns whether this typo correction is correcting to a declaration that was declared in a module tha...
void setCorrectionRange(CXXScopeSpec *SS, const DeclarationNameInfo &TypoName)
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
decl_iterator end()
void setCallbackDistance(unsigned ED)
decl_iterator begin()
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setRequiresImport(bool Req)
std::string getQuoted(const LangOptions &LO) const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:6585
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
unsigned size() const
void append(iterator I, iterator E)
void truncate(unsigned N)
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents C++ using-directive.
Definition: DeclCXX.h:3015
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition: DeclCXX.cpp:2958
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition: Decl.cpp:2691
Consumes visible declarations found when searching for all visible names within a given scope or cont...
Definition: Lookup.h:836
virtual bool includeHiddenDecls() const
Determine whether hidden declarations (from unimported modules) should be given to this consumer.
virtual ~VisibleDeclConsumer()
Destroys the visible declaration consumer.
bool isVisible(const Module *M) const
Determine whether a module is visible.
Definition: Module.h:835
SmallVector< SwitchInfo, 8 > SwitchStack
SwitchStack - This is the current set of active switch statements in the block.
Definition: ScopeInfo.h:209
Provides information about an attempted template argument deduction, whose success or failure was des...
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1393
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
std::unique_ptr< sema::RISCVIntrinsicManager > CreateRISCVIntrinsicManager(Sema &S)
@ SC_Extern
Definition: Specifiers.h:248
@ SC_None
Definition: Specifiers.h:247
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:65
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:425
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const FunctionProtoType * T
@ Success
Template argument deduction was successful.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ CC_C
Definition: Specifiers.h:276
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1241
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ EST_None
no exception specification
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
Represents an element in a path from a derived class to a base class.
int SubobjectNumber
Identifies which base class subobject (of type Base->getType()) this base path element refers to.
const CXXBaseSpecifier * Base
The base specifier that states the link from a derived class to a base class, which will be followed ...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
Extra information about a function prototype.
Definition: Type.h:4735
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4742
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4736
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57