Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaLookup.cpp
Warning:line 4215, column 37
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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