Bug Summary

File:clang/lib/Sema/SemaLookup.cpp
Warning:line 108, column 38
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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