Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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