blob: f8cb5f037ec0843ce70c568142d91a522c46122d [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Douglas Gregor42af25f2009-05-11 19:58:34 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000022#include "clang/AST/Expr.h"
Douglas Gregordaa439a2009-07-08 10:57:20 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000026#include "clang/Basic/LangOptions.h"
27#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000028#include "llvm/ADT/SmallPtrSet.h"
John McCall6e247262009-10-10 05:48:19 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000030#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000031#include <vector>
32#include <iterator>
33#include <utility>
34#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000035
36using namespace clang;
37
John McCalld7be78a2009-11-10 07:01:13 +000038namespace {
39 class UnqualUsingEntry {
40 const DeclContext *Nominated;
41 const DeclContext *CommonAncestor;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000042
John McCalld7be78a2009-11-10 07:01:13 +000043 public:
44 UnqualUsingEntry(const DeclContext *Nominated,
45 const DeclContext *CommonAncestor)
46 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
47 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000048
John McCalld7be78a2009-11-10 07:01:13 +000049 const DeclContext *getCommonAncestor() const {
50 return CommonAncestor;
51 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000052
John McCalld7be78a2009-11-10 07:01:13 +000053 const DeclContext *getNominatedNamespace() const {
54 return Nominated;
55 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000056
John McCalld7be78a2009-11-10 07:01:13 +000057 // Sort by the pointer value of the common ancestor.
58 struct Comparator {
59 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
60 return L.getCommonAncestor() < R.getCommonAncestor();
61 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000062
John McCalld7be78a2009-11-10 07:01:13 +000063 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
64 return E.getCommonAncestor() < DC;
65 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +000066
John McCalld7be78a2009-11-10 07:01:13 +000067 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
68 return DC < E.getCommonAncestor();
69 }
70 };
71 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +000072
John McCalld7be78a2009-11-10 07:01:13 +000073 /// A collection of using directives, as used by C++ unqualified
74 /// lookup.
75 class UnqualUsingDirectiveSet {
76 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000077
John McCalld7be78a2009-11-10 07:01:13 +000078 ListTy list;
79 llvm::SmallPtrSet<DeclContext*, 8> visited;
Douglas Gregor2a3009a2009-02-03 19:21:40 +000080
John McCalld7be78a2009-11-10 07:01:13 +000081 public:
82 UnqualUsingDirectiveSet() {}
Douglas Gregor2a3009a2009-02-03 19:21:40 +000083
John McCalld7be78a2009-11-10 07:01:13 +000084 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
85 // C++ [namespace.udir]p1:
86 // During unqualified name lookup, the names appear as if they
87 // were declared in the nearest enclosing namespace which contains
88 // both the using-directive and the nominated namespace.
89 DeclContext *InnermostFileDC
90 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
91 assert(InnermostFileDC && InnermostFileDC->isFileContext());
Douglas Gregor2a3009a2009-02-03 19:21:40 +000092
John McCalld7be78a2009-11-10 07:01:13 +000093 for (; S; S = S->getParent()) {
John McCalld7be78a2009-11-10 07:01:13 +000094 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
95 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
96 visit(Ctx, EffectiveDC);
97 } else {
98 Scope::udir_iterator I = S->using_directives_begin(),
99 End = S->using_directives_end();
100
101 for (; I != End; ++I)
102 visit(I->getAs<UsingDirectiveDecl>(), InnermostFileDC);
103 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000104 }
105 }
John McCalld7be78a2009-11-10 07:01:13 +0000106
107 // Visits a context and collect all of its using directives
108 // recursively. Treats all using directives as if they were
109 // declared in the context.
110 //
111 // A given context is only every visited once, so it is important
112 // that contexts be visited from the inside out in order to get
113 // the effective DCs right.
114 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
115 if (!visited.insert(DC))
116 return;
117
118 addUsingDirectives(DC, EffectiveDC);
119 }
120
121 // Visits a using directive and collects all of its using
122 // directives recursively. Treats all using directives as if they
123 // were declared in the effective DC.
124 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
125 DeclContext *NS = UD->getNominatedNamespace();
126 if (!visited.insert(NS))
127 return;
128
129 addUsingDirective(UD, EffectiveDC);
130 addUsingDirectives(NS, EffectiveDC);
131 }
132
133 // Adds all the using directives in a context (and those nominated
134 // by its using directives, transitively) as if they appeared in
135 // the given effective context.
136 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
137 llvm::SmallVector<DeclContext*,4> queue;
138 while (true) {
139 DeclContext::udir_iterator I, End;
140 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
141 UsingDirectiveDecl *UD = *I;
142 DeclContext *NS = UD->getNominatedNamespace();
143 if (visited.insert(NS)) {
144 addUsingDirective(UD, EffectiveDC);
145 queue.push_back(NS);
146 }
147 }
148
149 if (queue.empty())
150 return;
151
152 DC = queue.back();
153 queue.pop_back();
154 }
155 }
156
157 // Add a using directive as if it had been declared in the given
158 // context. This helps implement C++ [namespace.udir]p3:
159 // The using-directive is transitive: if a scope contains a
160 // using-directive that nominates a second namespace that itself
161 // contains using-directives, the effect is as if the
162 // using-directives from the second namespace also appeared in
163 // the first.
164 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
165 // Find the common ancestor between the effective context and
166 // the nominated namespace.
167 DeclContext *Common = UD->getNominatedNamespace();
168 while (!Common->Encloses(EffectiveDC))
169 Common = Common->getParent();
John McCall12ea5782009-11-10 09:20:04 +0000170 Common = Common->getPrimaryContext();
John McCalld7be78a2009-11-10 07:01:13 +0000171
172 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
173 }
174
175 void done() {
176 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
177 }
178
179 typedef ListTy::iterator iterator;
180 typedef ListTy::const_iterator const_iterator;
181
182 iterator begin() { return list.begin(); }
183 iterator end() { return list.end(); }
184 const_iterator begin() const { return list.begin(); }
185 const_iterator end() const { return list.end(); }
186
187 std::pair<const_iterator,const_iterator>
188 getNamespacesFor(DeclContext *DC) const {
John McCall12ea5782009-11-10 09:20:04 +0000189 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
John McCalld7be78a2009-11-10 07:01:13 +0000190 UnqualUsingEntry::Comparator());
191 }
192 };
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000193}
194
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000195// Retrieve the set of identifier namespaces that correspond to a
196// specific kind of name lookup.
Mike Stump1eb44332009-09-09 15:08:12 +0000197inline unsigned
198getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000199 bool CPlusPlus) {
200 unsigned IDNS = 0;
201 switch (NameKind) {
202 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000203 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000204 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000205 IDNS = Decl::IDNS_Ordinary;
206 if (CPlusPlus)
207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
208 break;
209
210 case Sema::LookupTagName:
211 IDNS = Decl::IDNS_Tag;
212 break;
213
214 case Sema::LookupMemberName:
215 IDNS = Decl::IDNS_Member;
216 if (CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000218 break;
219
220 case Sema::LookupNestedNameSpecifierName:
221 case Sema::LookupNamespaceName:
222 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
223 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000224
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000225 case Sema::LookupObjCProtocolName:
226 IDNS = Decl::IDNS_ObjCProtocol;
227 break;
228
229 case Sema::LookupObjCImplementationName:
230 IDNS = Decl::IDNS_ObjCImplementation;
231 break;
232
233 case Sema::LookupObjCCategoryImplName:
234 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000235 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000236 }
237 return IDNS;
238}
239
John McCallf36e02d2009-10-09 21:13:30 +0000240// Necessary because CXXBasePaths is not complete in Sema.h
John McCall7d384dd2009-11-18 07:57:50 +0000241void LookupResult::deletePaths(CXXBasePaths *Paths) {
John McCallf36e02d2009-10-09 21:13:30 +0000242 delete Paths;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000243}
244
John McCall7453ed42009-11-22 00:44:51 +0000245/// Resolves the result kind of this lookup.
John McCall7d384dd2009-11-18 07:57:50 +0000246void LookupResult::resolveKind() {
John McCallf36e02d2009-10-09 21:13:30 +0000247 unsigned N = Decls.size();
Douglas Gregor69d993a2009-01-17 01:13:24 +0000248
John McCallf36e02d2009-10-09 21:13:30 +0000249 // Fast case: no possible ambiguity.
John McCall68263142009-11-18 22:49:29 +0000250 if (N == 0) {
251 assert(ResultKind == NotFound);
252 return;
253 }
254
John McCall7453ed42009-11-22 00:44:51 +0000255 // If there's a single decl, we need to examine it to decide what
256 // kind of lookup this is.
John McCall7ba107a2009-11-18 02:36:19 +0000257 if (N == 1) {
John McCall7453ed42009-11-22 00:44:51 +0000258 if (isa<FunctionTemplateDecl>(Decls[0]))
259 ResultKind = FoundOverloaded;
260 else if (isa<UnresolvedUsingValueDecl>(Decls[0]))
John McCall7ba107a2009-11-18 02:36:19 +0000261 ResultKind = FoundUnresolvedValue;
262 return;
263 }
John McCallf36e02d2009-10-09 21:13:30 +0000264
John McCall6e247262009-10-10 05:48:19 +0000265 // Don't do any extra resolution if we've already resolved as ambiguous.
John McCalla24dc2e2009-11-17 02:14:36 +0000266 if (ResultKind == Ambiguous) return;
John McCall6e247262009-10-10 05:48:19 +0000267
John McCallf36e02d2009-10-09 21:13:30 +0000268 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
269
270 bool Ambiguous = false;
271 bool HasTag = false, HasFunction = false, HasNonFunction = false;
John McCall7453ed42009-11-22 00:44:51 +0000272 bool HasFunctionTemplate = false, HasUnresolved = false;
John McCallf36e02d2009-10-09 21:13:30 +0000273
274 unsigned UniqueTagIndex = 0;
275
276 unsigned I = 0;
277 while (I < N) {
John McCall314be4e2009-11-17 07:50:12 +0000278 NamedDecl *D = Decls[I]->getUnderlyingDecl();
279 D = cast<NamedDecl>(D->getCanonicalDecl());
John McCallf36e02d2009-10-09 21:13:30 +0000280
John McCall314be4e2009-11-17 07:50:12 +0000281 if (!Unique.insert(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000282 // If it's not unique, pull something off the back (and
283 // continue at this index).
284 Decls[I] = Decls[--N];
John McCall7ba107a2009-11-18 02:36:19 +0000285 } else if (isa<UnresolvedUsingValueDecl>(D)) {
286 // FIXME: support unresolved using value declarations
John McCallf36e02d2009-10-09 21:13:30 +0000287 Decls[I] = Decls[--N];
288 } else {
289 // Otherwise, do some decl type analysis and then continue.
John McCall7ba107a2009-11-18 02:36:19 +0000290
291 if (isa<UnresolvedUsingValueDecl>(D)) {
292 HasUnresolved = true;
293 } else if (isa<TagDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000294 if (HasTag)
295 Ambiguous = true;
296 UniqueTagIndex = I;
297 HasTag = true;
John McCall7453ed42009-11-22 00:44:51 +0000298 } else if (isa<FunctionTemplateDecl>(D)) {
299 HasFunction = true;
300 HasFunctionTemplate = true;
301 } else if (isa<FunctionDecl>(D)) {
John McCallf36e02d2009-10-09 21:13:30 +0000302 HasFunction = true;
303 } else {
304 if (HasNonFunction)
305 Ambiguous = true;
306 HasNonFunction = true;
307 }
308 I++;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000309 }
Mike Stump1eb44332009-09-09 15:08:12 +0000310 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000311
John McCallf36e02d2009-10-09 21:13:30 +0000312 // C++ [basic.scope.hiding]p2:
313 // A class name or enumeration name can be hidden by the name of
314 // an object, function, or enumerator declared in the same
315 // scope. If a class or enumeration name and an object, function,
316 // or enumerator are declared in the same scope (in any order)
317 // with the same name, the class or enumeration name is hidden
318 // wherever the object, function, or enumerator name is visible.
319 // But it's still an error if there are distinct tag types found,
320 // even if they're not visible. (ref?)
John McCall7ba107a2009-11-18 02:36:19 +0000321 if (HideTags && HasTag && !Ambiguous && !HasUnresolved &&
322 (HasFunction || HasNonFunction))
John McCallf36e02d2009-10-09 21:13:30 +0000323 Decls[UniqueTagIndex] = Decls[--N];
Anders Carlsson8b50d012009-06-26 03:37:05 +0000324
John McCallf36e02d2009-10-09 21:13:30 +0000325 Decls.set_size(N);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000326
John McCallf36e02d2009-10-09 21:13:30 +0000327 if (HasFunction && HasNonFunction)
328 Ambiguous = true;
Douglas Gregor69d993a2009-01-17 01:13:24 +0000329
John McCallf36e02d2009-10-09 21:13:30 +0000330 if (Ambiguous)
John McCall6e247262009-10-10 05:48:19 +0000331 setAmbiguous(LookupResult::AmbiguousReference);
John McCall7ba107a2009-11-18 02:36:19 +0000332 else if (HasUnresolved)
333 ResultKind = LookupResult::FoundUnresolvedValue;
John McCall7453ed42009-11-22 00:44:51 +0000334 else if (N > 1 || HasFunctionTemplate)
John McCalla24dc2e2009-11-17 02:14:36 +0000335 ResultKind = LookupResult::FoundOverloaded;
John McCallf36e02d2009-10-09 21:13:30 +0000336 else
John McCalla24dc2e2009-11-17 02:14:36 +0000337 ResultKind = LookupResult::Found;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000338}
339
John McCall7d384dd2009-11-18 07:57:50 +0000340void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000341 CXXBasePaths::paths_iterator I, E;
342 DeclContext::lookup_iterator DI, DE;
343 for (I = P.begin(), E = P.end(); I != E; ++I)
344 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
345 addDecl(*DI);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000346}
347
John McCall7d384dd2009-11-18 07:57:50 +0000348void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000349 Paths = new CXXBasePaths;
350 Paths->swap(P);
351 addDeclsFromBasePaths(*Paths);
352 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000353 setAmbiguous(AmbiguousBaseSubobjects);
Douglas Gregord8635172009-02-02 21:35:47 +0000354}
355
John McCall7d384dd2009-11-18 07:57:50 +0000356void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
John McCallf36e02d2009-10-09 21:13:30 +0000357 Paths = new CXXBasePaths;
358 Paths->swap(P);
359 addDeclsFromBasePaths(*Paths);
360 resolveKind();
John McCall6e247262009-10-10 05:48:19 +0000361 setAmbiguous(AmbiguousBaseSubobjectTypes);
John McCallf36e02d2009-10-09 21:13:30 +0000362}
363
John McCall7d384dd2009-11-18 07:57:50 +0000364void LookupResult::print(llvm::raw_ostream &Out) {
John McCallf36e02d2009-10-09 21:13:30 +0000365 Out << Decls.size() << " result(s)";
366 if (isAmbiguous()) Out << ", ambiguous";
367 if (Paths) Out << ", base paths present";
368
369 for (iterator I = begin(), E = end(); I != E; ++I) {
370 Out << "\n";
371 (*I)->print(Out, 2);
372 }
373}
374
375// Adds all qualifying matches for a name within a decl context to the
376// given lookup result. Returns true if any matches were found.
John McCall7d384dd2009-11-18 07:57:50 +0000377static bool LookupDirect(LookupResult &R, const DeclContext *DC) {
John McCallf36e02d2009-10-09 21:13:30 +0000378 bool Found = false;
379
John McCalld7be78a2009-11-10 07:01:13 +0000380 DeclContext::lookup_const_iterator I, E;
John McCalla24dc2e2009-11-17 02:14:36 +0000381 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I)
382 if (Sema::isAcceptableLookupResult(*I, R.getLookupKind(),
383 R.getIdentifierNamespace()))
John McCallf36e02d2009-10-09 21:13:30 +0000384 R.addDecl(*I), Found = true;
385
386 return Found;
387}
388
John McCalld7be78a2009-11-10 07:01:13 +0000389// Performs C++ unqualified lookup into the given file context.
John McCallf36e02d2009-10-09 21:13:30 +0000390static bool
John McCall7d384dd2009-11-18 07:57:50 +0000391CppNamespaceLookup(LookupResult &R, ASTContext &Context, DeclContext *NS,
John McCalla24dc2e2009-11-17 02:14:36 +0000392 UnqualUsingDirectiveSet &UDirs) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000393
394 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
395
John McCalld7be78a2009-11-10 07:01:13 +0000396 // Perform direct name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000397 bool Found = LookupDirect(R, NS);
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000398
John McCalld7be78a2009-11-10 07:01:13 +0000399 // Perform direct name lookup into the namespaces nominated by the
400 // using directives whose common ancestor is this namespace.
401 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
402 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
Mike Stump1eb44332009-09-09 15:08:12 +0000403
John McCalld7be78a2009-11-10 07:01:13 +0000404 for (; UI != UEnd; ++UI)
John McCalla24dc2e2009-11-17 02:14:36 +0000405 if (LookupDirect(R, UI->getNominatedNamespace()))
John McCalld7be78a2009-11-10 07:01:13 +0000406 Found = true;
John McCallf36e02d2009-10-09 21:13:30 +0000407
408 R.resolveKind();
409
410 return Found;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000411}
412
413static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000414 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000415 return Ctx->isFileContext();
416 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000417}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000418
Douglas Gregore942bbe2009-09-10 16:57:35 +0000419// Find the next outer declaration context corresponding to this scope.
420static DeclContext *findOuterContext(Scope *S) {
421 for (S = S->getParent(); S; S = S->getParent())
422 if (S->getEntity())
423 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
424
425 return 0;
426}
427
John McCalla24dc2e2009-11-17 02:14:36 +0000428bool Sema::CppLookupName(LookupResult &R, Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000429 assert(getLangOptions().CPlusPlus &&
430 "Can perform only C++ lookup");
John McCalla24dc2e2009-11-17 02:14:36 +0000431 LookupNameKind NameKind = R.getLookupKind();
Mike Stump1eb44332009-09-09 15:08:12 +0000432 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000433 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
John McCall02cace72009-08-28 07:59:38 +0000434
435 // If we're testing for redeclarations, also look in the friend namespaces.
John McCalla24dc2e2009-11-17 02:14:36 +0000436 if (R.isForRedeclaration()) {
John McCall02cace72009-08-28 07:59:38 +0000437 if (IDNS & Decl::IDNS_Tag) IDNS |= Decl::IDNS_TagFriend;
438 if (IDNS & Decl::IDNS_Ordinary) IDNS |= Decl::IDNS_OrdinaryFriend;
439 }
440
John McCalla24dc2e2009-11-17 02:14:36 +0000441 R.setIdentifierNamespace(IDNS);
442
443 DeclarationName Name = R.getLookupName();
444
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000445 Scope *Initial = S;
Mike Stump1eb44332009-09-09 15:08:12 +0000446 IdentifierResolver::iterator
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000447 I = IdResolver.begin(Name),
448 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000449
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000450 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000451 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000452 // ...During unqualified name lookup (3.4.1), the names appear as if
453 // they were declared in the nearest enclosing namespace which contains
454 // both the using-directive and the nominated namespace.
Eli Friedman33a31382009-08-05 19:21:58 +0000455 // [Note: in this context, "contains" means "contains directly or
Mike Stump1eb44332009-09-09 15:08:12 +0000456 // indirectly".
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000457 //
458 // For example:
459 // namespace A { int i; }
460 // void foo() {
461 // int i;
462 // {
463 // using namespace A;
464 // ++i; // finds local 'i', A::i appears at global scope
465 // }
466 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000467 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000468 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000469 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000470 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000471 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000472 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
John McCallf36e02d2009-10-09 21:13:30 +0000473 Found = true;
474 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000475 }
476 }
John McCallf36e02d2009-10-09 21:13:30 +0000477 if (Found) {
478 R.resolveKind();
479 return true;
480 }
481
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000482 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
Douglas Gregore942bbe2009-09-10 16:57:35 +0000483 DeclContext *OuterCtx = findOuterContext(S);
484 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
485 Ctx = Ctx->getLookupParent()) {
486 if (Ctx->isFunctionOrMethod())
487 continue;
488
489 // Perform qualified name lookup into this context.
490 // FIXME: In some cases, we know that every name that could be found by
491 // this qualified name lookup will also be on the identifier chain. For
492 // example, inside a class without any base classes, we never need to
493 // perform qualified lookup because all of the members are on top of the
494 // identifier chain.
John McCalla24dc2e2009-11-17 02:14:36 +0000495 if (LookupQualifiedName(R, Ctx))
John McCallf36e02d2009-10-09 21:13:30 +0000496 return true;
Douglas Gregor551f48c2009-03-27 04:21:56 +0000497 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000498 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000499 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000500
John McCalld7be78a2009-11-10 07:01:13 +0000501 // Stop if we ran out of scopes.
502 // FIXME: This really, really shouldn't be happening.
503 if (!S) return false;
504
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000505 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000506 // nominated namespaces by those using-directives.
John McCalld7be78a2009-11-10 07:01:13 +0000507 //
Mike Stump390b4cc2009-05-16 07:39:55 +0000508 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
509 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000510
John McCalld7be78a2009-11-10 07:01:13 +0000511 UnqualUsingDirectiveSet UDirs;
512 UDirs.visitScopeChain(Initial, S);
513 UDirs.done();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000514
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000515 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000516 // Unqualified name lookup in C++ requires looking into scopes
517 // that aren't strictly lexical, and therefore we walk through the
518 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000519
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000520 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000521 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Douglas Gregora24eb4e2009-08-24 18:55:03 +0000522 if (Ctx->isTransparentContext())
523 continue;
524
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000525 assert(Ctx && Ctx->isFileContext() &&
526 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000527
528 // Check whether the IdResolver has anything in this scope.
John McCallf36e02d2009-10-09 21:13:30 +0000529 bool Found = false;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000530 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000531 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
532 // We found something. Look for anything else in our scope
533 // with this same name and in an acceptable identifier
534 // namespace, so that we can construct an overload set if we
535 // need to.
John McCallf36e02d2009-10-09 21:13:30 +0000536 Found = true;
537 R.addDecl(*I);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000538 }
539 }
540
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000541 // Look into context considering using-directives.
John McCalla24dc2e2009-11-17 02:14:36 +0000542 if (CppNamespaceLookup(R, Context, Ctx, UDirs))
John McCallf36e02d2009-10-09 21:13:30 +0000543 Found = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000544
John McCallf36e02d2009-10-09 21:13:30 +0000545 if (Found) {
546 R.resolveKind();
547 return true;
548 }
549
John McCalla24dc2e2009-11-17 02:14:36 +0000550 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
John McCallf36e02d2009-10-09 21:13:30 +0000551 return false;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000552 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000553
John McCallf36e02d2009-10-09 21:13:30 +0000554 return !R.empty();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000555}
556
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000557/// @brief Perform unqualified name lookup starting from a given
558/// scope.
559///
560/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
561/// used to find names within the current scope. For example, 'x' in
562/// @code
563/// int x;
564/// int f() {
565/// return x; // unqualified name look finds 'x' in the global scope
566/// }
567/// @endcode
568///
569/// Different lookup criteria can find different names. For example, a
570/// particular scope can have both a struct and a function of the same
571/// name, and each can be found by certain lookup criteria. For more
572/// information about lookup criteria, see the documentation for the
573/// class LookupCriteria.
574///
575/// @param S The scope from which unqualified name lookup will
576/// begin. If the lookup criteria permits, name lookup may also search
577/// in the parent scopes.
578///
579/// @param Name The name of the entity that we are searching for.
580///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000581/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +0000582/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +0000583/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000584///
585/// @returns The result of name lookup, which includes zero or more
586/// declarations and possibly additional information used to diagnose
587/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000588bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
589 DeclarationName Name = R.getLookupName();
John McCallf36e02d2009-10-09 21:13:30 +0000590 if (!Name) return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000591
John McCalla24dc2e2009-11-17 02:14:36 +0000592 LookupNameKind NameKind = R.getLookupKind();
593
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000594 if (!getLangOptions().CPlusPlus) {
595 // Unqualified name lookup in C/Objective-C is purely lexical, so
596 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000597 unsigned IDNS = 0;
598 switch (NameKind) {
599 case Sema::LookupOrdinaryName:
600 IDNS = Decl::IDNS_Ordinary;
601 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000602
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000603 case Sema::LookupTagName:
604 IDNS = Decl::IDNS_Tag;
605 break;
606
607 case Sema::LookupMemberName:
608 IDNS = Decl::IDNS_Member;
609 break;
610
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000611 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000612 case Sema::LookupNestedNameSpecifierName:
613 case Sema::LookupNamespaceName:
614 assert(false && "C does not perform these kinds of name lookup");
615 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000616
617 case Sema::LookupRedeclarationWithLinkage:
618 // Find the nearest non-transparent declaration scope.
619 while (!(S->getFlags() & Scope::DeclScope) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000620 (S->getEntity() &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000621 static_cast<DeclContext *>(S->getEntity())
622 ->isTransparentContext()))
623 S = S->getParent();
624 IDNS = Decl::IDNS_Ordinary;
625 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000626
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000627 case Sema::LookupObjCProtocolName:
628 IDNS = Decl::IDNS_ObjCProtocol;
629 break;
630
631 case Sema::LookupObjCImplementationName:
632 IDNS = Decl::IDNS_ObjCImplementation;
633 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000635 case Sema::LookupObjCCategoryImplName:
636 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000637 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000638 }
639
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000640 // Scan up the scope chain looking for a decl that matches this
641 // identifier that is in the appropriate namespace. This search
642 // should not take long, as shadowing of names is uncommon, and
643 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000644 bool LeftStartingScope = false;
645
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000646 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
Mike Stump1eb44332009-09-09 15:08:12 +0000647 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000648 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000649 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000650 if (NameKind == LookupRedeclarationWithLinkage) {
651 // Determine whether this (or a previous) declaration is
652 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000653 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000654 LeftStartingScope = true;
655
656 // If we found something outside of our starting scope that
657 // does not have linkage, skip it.
658 if (LeftStartingScope && !((*I)->hasLinkage()))
659 continue;
660 }
661
John McCallf36e02d2009-10-09 21:13:30 +0000662 R.addDecl(*I);
663
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000664 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000665 // If this declaration has the "overloadable" attribute, we
666 // might have a set of overloaded functions.
667
668 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000669 while (!(S->getFlags() & Scope::DeclScope) ||
670 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000671 S = S->getParent();
672
673 // Find the last declaration in this scope (with the same
674 // name, naturally).
675 IdentifierResolver::iterator LastI = I;
676 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000677 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000678 break;
John McCallf36e02d2009-10-09 21:13:30 +0000679 R.addDecl(*LastI);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000680 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000681 }
682
John McCallf36e02d2009-10-09 21:13:30 +0000683 R.resolveKind();
684
685 return true;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000686 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000687 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000688 // Perform C++ unqualified name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000689 if (CppLookupName(R, S))
John McCallf36e02d2009-10-09 21:13:30 +0000690 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000691 }
692
693 // If we didn't find a use of this identifier, and if the identifier
694 // corresponds to a compiler builtin, create the decl object for the builtin
695 // now, injecting it into translation unit scope, and return it.
Mike Stump1eb44332009-09-09 15:08:12 +0000696 if (NameKind == LookupOrdinaryName ||
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000697 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000698 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000699 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000700 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000701 if (unsigned BuiltinID = II->getBuiltinID()) {
702 // In C++, we don't have any predefined library functions like
703 // 'malloc'. Instead, we'll just error.
Mike Stump1eb44332009-09-09 15:08:12 +0000704 if (getLangOptions().CPlusPlus &&
Douglas Gregor3e41d602009-02-13 23:20:09 +0000705 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
John McCallf36e02d2009-10-09 21:13:30 +0000706 return false;
Douglas Gregor3e41d602009-02-13 23:20:09 +0000707
John McCallf36e02d2009-10-09 21:13:30 +0000708 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
John McCalla24dc2e2009-11-17 02:14:36 +0000709 S, R.isForRedeclaration(),
710 R.getNameLoc());
John McCallf36e02d2009-10-09 21:13:30 +0000711 if (D) R.addDecl(D);
712 return (D != NULL);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000713 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000714 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000715 }
John McCallf36e02d2009-10-09 21:13:30 +0000716 return false;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000717}
718
John McCall6e247262009-10-10 05:48:19 +0000719/// @brief Perform qualified name lookup in the namespaces nominated by
720/// using directives by the given context.
721///
722/// C++98 [namespace.qual]p2:
723/// Given X::m (where X is a user-declared namespace), or given ::m
724/// (where X is the global namespace), let S be the set of all
725/// declarations of m in X and in the transitive closure of all
726/// namespaces nominated by using-directives in X and its used
727/// namespaces, except that using-directives are ignored in any
728/// namespace, including X, directly containing one or more
729/// declarations of m. No namespace is searched more than once in
730/// the lookup of a name. If S is the empty set, the program is
731/// ill-formed. Otherwise, if S has exactly one member, or if the
732/// context of the reference is a using-declaration
733/// (namespace.udecl), S is the required set of declarations of
734/// m. Otherwise if the use of m is not one that allows a unique
735/// declaration to be chosen from S, the program is ill-formed.
736/// C++98 [namespace.qual]p5:
737/// During the lookup of a qualified namespace member name, if the
738/// lookup finds more than one declaration of the member, and if one
739/// declaration introduces a class name or enumeration name and the
740/// other declarations either introduce the same object, the same
741/// enumerator or a set of functions, the non-type name hides the
742/// class or enumeration name if and only if the declarations are
743/// from the same namespace; otherwise (the declarations are from
744/// different namespaces), the program is ill-formed.
John McCall7d384dd2009-11-18 07:57:50 +0000745static bool LookupQualifiedNameInUsingDirectives(LookupResult &R,
John McCalla24dc2e2009-11-17 02:14:36 +0000746 DeclContext *StartDC) {
John McCall6e247262009-10-10 05:48:19 +0000747 assert(StartDC->isFileContext() && "start context is not a file context");
748
749 DeclContext::udir_iterator I = StartDC->using_directives_begin();
750 DeclContext::udir_iterator E = StartDC->using_directives_end();
751
752 if (I == E) return false;
753
754 // We have at least added all these contexts to the queue.
755 llvm::DenseSet<DeclContext*> Visited;
756 Visited.insert(StartDC);
757
758 // We have not yet looked into these namespaces, much less added
759 // their "using-children" to the queue.
760 llvm::SmallVector<NamespaceDecl*, 8> Queue;
761
762 // We have already looked into the initial namespace; seed the queue
763 // with its using-children.
764 for (; I != E; ++I) {
John McCalld9f01d42009-11-10 09:25:37 +0000765 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
John McCall6e247262009-10-10 05:48:19 +0000766 if (Visited.insert(ND).second)
767 Queue.push_back(ND);
768 }
769
770 // The easiest way to implement the restriction in [namespace.qual]p5
771 // is to check whether any of the individual results found a tag
772 // and, if so, to declare an ambiguity if the final result is not
773 // a tag.
774 bool FoundTag = false;
775 bool FoundNonTag = false;
776
John McCall7d384dd2009-11-18 07:57:50 +0000777 LookupResult LocalR(LookupResult::Temporary, R);
John McCall6e247262009-10-10 05:48:19 +0000778
779 bool Found = false;
780 while (!Queue.empty()) {
781 NamespaceDecl *ND = Queue.back();
782 Queue.pop_back();
783
784 // We go through some convolutions here to avoid copying results
785 // between LookupResults.
786 bool UseLocal = !R.empty();
John McCall7d384dd2009-11-18 07:57:50 +0000787 LookupResult &DirectR = UseLocal ? LocalR : R;
John McCalla24dc2e2009-11-17 02:14:36 +0000788 bool FoundDirect = LookupDirect(DirectR, ND);
John McCall6e247262009-10-10 05:48:19 +0000789
790 if (FoundDirect) {
791 // First do any local hiding.
792 DirectR.resolveKind();
793
794 // If the local result is a tag, remember that.
795 if (DirectR.isSingleTagDecl())
796 FoundTag = true;
797 else
798 FoundNonTag = true;
799
800 // Append the local results to the total results if necessary.
801 if (UseLocal) {
802 R.addAllDecls(LocalR);
803 LocalR.clear();
804 }
805 }
806
807 // If we find names in this namespace, ignore its using directives.
808 if (FoundDirect) {
809 Found = true;
810 continue;
811 }
812
813 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
814 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
815 if (Visited.insert(Nom).second)
816 Queue.push_back(Nom);
817 }
818 }
819
820 if (Found) {
821 if (FoundTag && FoundNonTag)
822 R.setAmbiguousQualifiedTagHiding();
823 else
824 R.resolveKind();
825 }
826
827 return Found;
828}
829
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000830/// @brief Perform qualified name lookup into a given context.
831///
832/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
833/// names when the context of those names is explicit specified, e.g.,
834/// "std::vector" or "x->member".
835///
836/// Different lookup criteria can find different names. For example, a
837/// particular scope can have both a struct and a function of the same
838/// name, and each can be found by certain lookup criteria. For more
839/// information about lookup criteria, see the documentation for the
840/// class LookupCriteria.
841///
842/// @param LookupCtx The context in which qualified name lookup will
843/// search. If the lookup criteria permits, name lookup may also search
844/// in the parent contexts or (for C++ classes) base classes.
845///
846/// @param Name The name of the entity that we are searching for.
847///
848/// @param Criteria The criteria that this routine will use to
849/// determine which names are visible and which names will be
850/// found. Note that name lookup will find a name that is visible by
851/// the given criteria, but the entity itself may not be semantically
852/// correct or even the kind of entity expected based on the
853/// lookup. For example, searching for a nested-name-specifier name
854/// might result in an EnumDecl, which is visible but is not permitted
855/// as a nested-name-specifier in C++03.
856///
857/// @returns The result of name lookup, which includes zero or more
858/// declarations and possibly additional information used to diagnose
859/// ambiguities.
John McCalla24dc2e2009-11-17 02:14:36 +0000860bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000861 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
Mike Stump1eb44332009-09-09 15:08:12 +0000862
John McCalla24dc2e2009-11-17 02:14:36 +0000863 if (!R.getLookupName())
John McCallf36e02d2009-10-09 21:13:30 +0000864 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000866 // If we're performing qualified name lookup (e.g., lookup into a
867 // struct), find fields as part of ordinary name lookup.
John McCalla24dc2e2009-11-17 02:14:36 +0000868 LookupNameKind NameKind = R.getLookupKind();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000869 unsigned IDNS
Mike Stump1eb44332009-09-09 15:08:12 +0000870 = getIdentifierNamespacesFromLookupNameKind(NameKind,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000871 getLangOptions().CPlusPlus);
872 if (NameKind == LookupOrdinaryName)
873 IDNS |= Decl::IDNS_Member;
Mike Stump1eb44332009-09-09 15:08:12 +0000874
John McCalla24dc2e2009-11-17 02:14:36 +0000875 R.setIdentifierNamespace(IDNS);
876
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000877 // Make sure that the declaration context is complete.
878 assert((!isa<TagDecl>(LookupCtx) ||
879 LookupCtx->isDependentContext() ||
880 cast<TagDecl>(LookupCtx)->isDefinition() ||
881 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
882 ->isBeingDefined()) &&
883 "Declaration context must already be complete!");
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000885 // Perform qualified name lookup into the LookupCtx.
John McCalla24dc2e2009-11-17 02:14:36 +0000886 if (LookupDirect(R, LookupCtx)) {
John McCallf36e02d2009-10-09 21:13:30 +0000887 R.resolveKind();
888 return true;
889 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000890
John McCall6e247262009-10-10 05:48:19 +0000891 // Don't descend into implied contexts for redeclarations.
892 // C++98 [namespace.qual]p6:
893 // In a declaration for a namespace member in which the
894 // declarator-id is a qualified-id, given that the qualified-id
895 // for the namespace member has the form
896 // nested-name-specifier unqualified-id
897 // the unqualified-id shall name a member of the namespace
898 // designated by the nested-name-specifier.
899 // See also [class.mfct]p5 and [class.static.data]p2.
John McCalla24dc2e2009-11-17 02:14:36 +0000900 if (R.isForRedeclaration())
John McCall6e247262009-10-10 05:48:19 +0000901 return false;
902
John McCalla24dc2e2009-11-17 02:14:36 +0000903 // If this is a namespace, look it up in the implied namespaces.
John McCall6e247262009-10-10 05:48:19 +0000904 if (LookupCtx->isFileContext())
John McCalla24dc2e2009-11-17 02:14:36 +0000905 return LookupQualifiedNameInUsingDirectives(R, LookupCtx);
John McCall6e247262009-10-10 05:48:19 +0000906
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000907 // If this isn't a C++ class, we aren't allowed to look into base
Douglas Gregor4719f4e2009-09-11 22:57:37 +0000908 // classes, we're done.
John McCall6e247262009-10-10 05:48:19 +0000909 if (!isa<CXXRecordDecl>(LookupCtx))
John McCallf36e02d2009-10-09 21:13:30 +0000910 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000911
912 // Perform lookup into our base classes.
Douglas Gregora8f32e02009-10-06 17:59:45 +0000913 CXXRecordDecl *LookupRec = cast<CXXRecordDecl>(LookupCtx);
914 CXXBasePaths Paths;
915 Paths.setOrigin(LookupRec);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000916
917 // Look for this member in our base classes
Douglas Gregora8f32e02009-10-06 17:59:45 +0000918 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000919 switch (R.getLookupKind()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000920 case LookupOrdinaryName:
921 case LookupMemberName:
922 case LookupRedeclarationWithLinkage:
923 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
924 break;
925
926 case LookupTagName:
927 BaseCallback = &CXXRecordDecl::FindTagMember;
928 break;
929
930 case LookupOperatorName:
931 case LookupNamespaceName:
932 case LookupObjCProtocolName:
933 case LookupObjCImplementationName:
934 case LookupObjCCategoryImplName:
935 // These lookups will never find a member in a C++ class (or base class).
John McCallf36e02d2009-10-09 21:13:30 +0000936 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000937
938 case LookupNestedNameSpecifierName:
939 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
940 break;
941 }
942
John McCalla24dc2e2009-11-17 02:14:36 +0000943 if (!LookupRec->lookupInBases(BaseCallback,
944 R.getLookupName().getAsOpaquePtr(), Paths))
John McCallf36e02d2009-10-09 21:13:30 +0000945 return false;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000946
947 // C++ [class.member.lookup]p2:
948 // [...] If the resulting set of declarations are not all from
949 // sub-objects of the same type, or the set has a nonstatic member
950 // and includes members from distinct sub-objects, there is an
951 // ambiguity and the program is ill-formed. Otherwise that set is
952 // the result of the lookup.
953 // FIXME: support using declarations!
954 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +0000955 int SubobjectNumber = 0;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000956 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000957 Path != PathEnd; ++Path) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000958 const CXXBasePathElement &PathElement = Path->back();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000959
960 // Determine whether we're looking at a distinct sub-object or not.
961 if (SubobjectType.isNull()) {
John McCallf36e02d2009-10-09 21:13:30 +0000962 // This is the first subobject we've looked at. Record its type.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000963 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
964 SubobjectNumber = PathElement.SubobjectNumber;
Mike Stump1eb44332009-09-09 15:08:12 +0000965 } else if (SubobjectType
Douglas Gregor7176fff2009-01-15 00:26:24 +0000966 != Context.getCanonicalType(PathElement.Base->getType())) {
967 // We found members of the given name in two subobjects of
968 // different types. This lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +0000969 R.setAmbiguousBaseSubobjectTypes(Paths);
970 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000971 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
972 // We have a different subobject of the same type.
973
974 // C++ [class.member.lookup]p5:
975 // A static member, a nested type or an enumerator defined in
976 // a base class T can unambiguously be found even if an object
Mike Stump1eb44332009-09-09 15:08:12 +0000977 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000978 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000979 if (isa<VarDecl>(FirstDecl) ||
980 isa<TypeDecl>(FirstDecl) ||
981 isa<EnumConstantDecl>(FirstDecl))
982 continue;
983
984 if (isa<CXXMethodDecl>(FirstDecl)) {
985 // Determine whether all of the methods are static.
986 bool AllMethodsAreStatic = true;
987 for (DeclContext::lookup_iterator Func = Path->Decls.first;
988 Func != Path->Decls.second; ++Func) {
989 if (!isa<CXXMethodDecl>(*Func)) {
990 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
991 break;
992 }
993
994 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
995 AllMethodsAreStatic = false;
996 break;
997 }
998 }
999
1000 if (AllMethodsAreStatic)
1001 continue;
1002 }
1003
1004 // We have found a nonstatic member name in multiple, distinct
1005 // subobjects. Name lookup is ambiguous.
John McCallf36e02d2009-10-09 21:13:30 +00001006 R.setAmbiguousBaseSubobjects(Paths);
1007 return true;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001008 }
1009 }
1010
1011 // Lookup in a base class succeeded; return these results.
1012
John McCallf36e02d2009-10-09 21:13:30 +00001013 DeclContext::lookup_iterator I, E;
1014 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I)
1015 R.addDecl(*I);
1016 R.resolveKind();
1017 return true;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001018}
1019
1020/// @brief Performs name lookup for a name that was parsed in the
1021/// source code, and may contain a C++ scope specifier.
1022///
1023/// This routine is a convenience routine meant to be called from
1024/// contexts that receive a name and an optional C++ scope specifier
1025/// (e.g., "N::M::x"). It will then perform either qualified or
1026/// unqualified name lookup (with LookupQualifiedName or LookupName,
1027/// respectively) on the given name and return those results.
1028///
1029/// @param S The scope from which unqualified name lookup will
1030/// begin.
Mike Stump1eb44332009-09-09 15:08:12 +00001031///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001032/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001033///
1034/// @param Name The name of the entity that name lookup will
1035/// search for.
1036///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001037/// @param Loc If provided, the source location where we're performing
Mike Stump1eb44332009-09-09 15:08:12 +00001038/// name lookup. At present, this is only used to produce diagnostics when
Douglas Gregor3e41d602009-02-13 23:20:09 +00001039/// C library functions (like "malloc") are implicitly declared.
1040///
Douglas Gregor495c35d2009-08-25 22:51:20 +00001041/// @param EnteringContext Indicates whether we are going to enter the
1042/// context of the scope-specifier SS (if present).
1043///
John McCallf36e02d2009-10-09 21:13:30 +00001044/// @returns True if any decls were found (but possibly ambiguous)
1045bool Sema::LookupParsedName(LookupResult &R, Scope *S, const CXXScopeSpec *SS,
John McCalla24dc2e2009-11-17 02:14:36 +00001046 bool AllowBuiltinCreation, bool EnteringContext) {
Douglas Gregor495c35d2009-08-25 22:51:20 +00001047 if (SS && SS->isInvalid()) {
1048 // When the scope specifier is invalid, don't even look for
Douglas Gregor42af25f2009-05-11 19:58:34 +00001049 // anything.
John McCallf36e02d2009-10-09 21:13:30 +00001050 return false;
Douglas Gregor495c35d2009-08-25 22:51:20 +00001051 }
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Douglas Gregor495c35d2009-08-25 22:51:20 +00001053 if (SS && SS->isSet()) {
1054 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001055 // We have resolved the scope specifier to a particular declaration
Douglas Gregor495c35d2009-08-25 22:51:20 +00001056 // contex, and will perform name lookup in that context.
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001057 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS))
John McCallf36e02d2009-10-09 21:13:30 +00001058 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001059
John McCalla24dc2e2009-11-17 02:14:36 +00001060 R.setContextRange(SS->getRange());
1061
1062 return LookupQualifiedName(R, DC);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001063 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001064
Douglas Gregor495c35d2009-08-25 22:51:20 +00001065 // We could not resolve the scope specified to a specific declaration
Mike Stump1eb44332009-09-09 15:08:12 +00001066 // context, which means that SS refers to an unknown specialization.
Douglas Gregor495c35d2009-08-25 22:51:20 +00001067 // Name lookup can't find anything in this case.
John McCallf36e02d2009-10-09 21:13:30 +00001068 return false;
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001069 }
1070
Mike Stump1eb44332009-09-09 15:08:12 +00001071 // Perform unqualified name lookup starting in the given scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001072 return LookupName(R, S, AllowBuiltinCreation);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001073}
1074
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001075
Douglas Gregor7176fff2009-01-15 00:26:24 +00001076/// @brief Produce a diagnostic describing the ambiguity that resulted
1077/// from name lookup.
1078///
1079/// @param Result The ambiguous name lookup result.
Mike Stump1eb44332009-09-09 15:08:12 +00001080///
Douglas Gregor7176fff2009-01-15 00:26:24 +00001081/// @param Name The name of the entity that name lookup was
1082/// searching for.
1083///
1084/// @param NameLoc The location of the name within the source code.
1085///
1086/// @param LookupRange A source range that provides more
1087/// source-location information concerning the lookup itself. For
1088/// example, this range might highlight a nested-name-specifier that
1089/// precedes the name.
1090///
1091/// @returns true
John McCalla24dc2e2009-11-17 02:14:36 +00001092bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
Douglas Gregor7176fff2009-01-15 00:26:24 +00001093 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1094
John McCalla24dc2e2009-11-17 02:14:36 +00001095 DeclarationName Name = Result.getLookupName();
1096 SourceLocation NameLoc = Result.getNameLoc();
1097 SourceRange LookupRange = Result.getContextRange();
1098
John McCall6e247262009-10-10 05:48:19 +00001099 switch (Result.getAmbiguityKind()) {
1100 case LookupResult::AmbiguousBaseSubobjects: {
1101 CXXBasePaths *Paths = Result.getBasePaths();
1102 QualType SubobjectType = Paths->front().back().Base->getType();
1103 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1104 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1105 << LookupRange;
1106
1107 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1108 while (isa<CXXMethodDecl>(*Found) &&
1109 cast<CXXMethodDecl>(*Found)->isStatic())
1110 ++Found;
1111
1112 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1113
1114 return true;
1115 }
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001116
John McCall6e247262009-10-10 05:48:19 +00001117 case LookupResult::AmbiguousBaseSubobjectTypes: {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001118 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1119 << Name << LookupRange;
John McCall6e247262009-10-10 05:48:19 +00001120
1121 CXXBasePaths *Paths = Result.getBasePaths();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001122 std::set<Decl *> DeclsPrinted;
John McCall6e247262009-10-10 05:48:19 +00001123 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1124 PathEnd = Paths->end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001125 Path != PathEnd; ++Path) {
1126 Decl *D = *Path->Decls.first;
1127 if (DeclsPrinted.insert(D).second)
1128 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1129 }
1130
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001131 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001132 }
1133
John McCall6e247262009-10-10 05:48:19 +00001134 case LookupResult::AmbiguousTagHiding: {
1135 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
Douglas Gregor69d993a2009-01-17 01:13:24 +00001136
John McCall6e247262009-10-10 05:48:19 +00001137 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1138
1139 LookupResult::iterator DI, DE = Result.end();
1140 for (DI = Result.begin(); DI != DE; ++DI)
1141 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1142 TagDecls.insert(TD);
1143 Diag(TD->getLocation(), diag::note_hidden_tag);
1144 }
1145
1146 for (DI = Result.begin(); DI != DE; ++DI)
1147 if (!isa<TagDecl>(*DI))
1148 Diag((*DI)->getLocation(), diag::note_hiding_object);
1149
1150 // For recovery purposes, go ahead and implement the hiding.
1151 Result.hideDecls(TagDecls);
1152
1153 return true;
1154 }
1155
1156 case LookupResult::AmbiguousReference: {
1157 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
John McCallf36e02d2009-10-09 21:13:30 +00001158
John McCall6e247262009-10-10 05:48:19 +00001159 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1160 for (; DI != DE; ++DI)
1161 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
John McCallf36e02d2009-10-09 21:13:30 +00001162
John McCall6e247262009-10-10 05:48:19 +00001163 return true;
1164 }
1165 }
1166
1167 llvm::llvm_unreachable("unknown ambiguity kind");
Douglas Gregor7176fff2009-01-15 00:26:24 +00001168 return true;
1169}
Douglas Gregorfa047642009-02-04 00:32:51 +00001170
Mike Stump1eb44332009-09-09 15:08:12 +00001171static void
1172addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001173 ASTContext &Context,
1174 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001175 Sema::AssociatedClassSet &AssociatedClasses);
1176
1177static void CollectNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1178 DeclContext *Ctx) {
1179 if (Ctx->isFileContext())
1180 Namespaces.insert(Ctx);
1181}
Douglas Gregor69be8d62009-07-08 07:51:57 +00001182
Mike Stump1eb44332009-09-09 15:08:12 +00001183// \brief Add the associated classes and namespaces for argument-dependent
Douglas Gregor69be8d62009-07-08 07:51:57 +00001184// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
Mike Stump1eb44332009-09-09 15:08:12 +00001185static void
1186addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
Douglas Gregor69be8d62009-07-08 07:51:57 +00001187 ASTContext &Context,
1188 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001189 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001190 // C++ [basic.lookup.koenig]p2, last bullet:
Mike Stump1eb44332009-09-09 15:08:12 +00001191 // -- [...] ;
Douglas Gregor69be8d62009-07-08 07:51:57 +00001192 switch (Arg.getKind()) {
1193 case TemplateArgument::Null:
1194 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Douglas Gregor69be8d62009-07-08 07:51:57 +00001196 case TemplateArgument::Type:
1197 // [...] the namespaces and classes associated with the types of the
1198 // template arguments provided for template type parameters (excluding
1199 // template template parameters)
1200 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1201 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001202 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001203 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Douglas Gregor788cd062009-11-11 01:00:40 +00001205 case TemplateArgument::Template: {
Mike Stump1eb44332009-09-09 15:08:12 +00001206 // [...] the namespaces in which any template template arguments are
1207 // defined; and the classes in which any member templates used as
Douglas Gregor69be8d62009-07-08 07:51:57 +00001208 // template template arguments are defined.
Douglas Gregor788cd062009-11-11 01:00:40 +00001209 TemplateName Template = Arg.getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00001210 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor788cd062009-11-11 01:00:40 +00001211 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
Douglas Gregor69be8d62009-07-08 07:51:57 +00001212 DeclContext *Ctx = ClassTemplate->getDeclContext();
1213 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1214 AssociatedClasses.insert(EnclosingClass);
1215 // Add the associated namespace for this class.
1216 while (Ctx->isRecord())
1217 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001218 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001219 }
1220 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001221 }
1222
1223 case TemplateArgument::Declaration:
Douglas Gregor69be8d62009-07-08 07:51:57 +00001224 case TemplateArgument::Integral:
1225 case TemplateArgument::Expression:
Mike Stump1eb44332009-09-09 15:08:12 +00001226 // [Note: non-type template arguments do not contribute to the set of
Douglas Gregor69be8d62009-07-08 07:51:57 +00001227 // associated namespaces. ]
1228 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Douglas Gregor69be8d62009-07-08 07:51:57 +00001230 case TemplateArgument::Pack:
1231 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1232 PEnd = Arg.pack_end();
1233 P != PEnd; ++P)
1234 addAssociatedClassesAndNamespaces(*P, Context,
1235 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001236 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001237 break;
1238 }
1239}
1240
Douglas Gregorfa047642009-02-04 00:32:51 +00001241// \brief Add the associated classes and namespaces for
Mike Stump1eb44332009-09-09 15:08:12 +00001242// argument-dependent lookup with an argument of class type
1243// (C++ [basic.lookup.koenig]p2).
1244static void
1245addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
Douglas Gregorfa047642009-02-04 00:32:51 +00001246 ASTContext &Context,
1247 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001248 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001249 // C++ [basic.lookup.koenig]p2:
1250 // [...]
1251 // -- If T is a class type (including unions), its associated
1252 // classes are: the class itself; the class of which it is a
1253 // member, if any; and its direct and indirect base
1254 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001255 // which its associated classes are defined.
Douglas Gregorfa047642009-02-04 00:32:51 +00001256
1257 // Add the class of which it is a member, if any.
1258 DeclContext *Ctx = Class->getDeclContext();
1259 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1260 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001261 // Add the associated namespace for this class.
1262 while (Ctx->isRecord())
1263 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001264 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Douglas Gregorfa047642009-02-04 00:32:51 +00001266 // Add the class itself. If we've already seen this class, we don't
1267 // need to visit base classes.
1268 if (!AssociatedClasses.insert(Class))
1269 return;
1270
Mike Stump1eb44332009-09-09 15:08:12 +00001271 // -- If T is a template-id, its associated namespaces and classes are
1272 // the namespace in which the template is defined; for member
Douglas Gregor69be8d62009-07-08 07:51:57 +00001273 // templates, the member template’s class; the namespaces and classes
Mike Stump1eb44332009-09-09 15:08:12 +00001274 // associated with the types of the template arguments provided for
Douglas Gregor69be8d62009-07-08 07:51:57 +00001275 // template type parameters (excluding template template parameters); the
Mike Stump1eb44332009-09-09 15:08:12 +00001276 // namespaces in which any template template arguments are defined; and
1277 // the classes in which any member templates used as template template
1278 // arguments are defined. [Note: non-type template arguments do not
Douglas Gregor69be8d62009-07-08 07:51:57 +00001279 // contribute to the set of associated namespaces. ]
Mike Stump1eb44332009-09-09 15:08:12 +00001280 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor69be8d62009-07-08 07:51:57 +00001281 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1282 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1283 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1284 AssociatedClasses.insert(EnclosingClass);
1285 // Add the associated namespace for this class.
1286 while (Ctx->isRecord())
1287 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001288 CollectNamespace(AssociatedNamespaces, Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Douglas Gregor69be8d62009-07-08 07:51:57 +00001290 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1291 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1292 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1293 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001294 AssociatedClasses);
Douglas Gregor69be8d62009-07-08 07:51:57 +00001295 }
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Douglas Gregorfa047642009-02-04 00:32:51 +00001297 // Add direct and indirect base classes along with their associated
1298 // namespaces.
1299 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1300 Bases.push_back(Class);
1301 while (!Bases.empty()) {
1302 // Pop this class off the stack.
1303 Class = Bases.back();
1304 Bases.pop_back();
1305
1306 // Visit the base classes.
1307 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1308 BaseEnd = Class->bases_end();
1309 Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Sebastian Redlbbc1cc52009-10-25 09:35:33 +00001311 // In dependent contexts, we do ADL twice, and the first time around,
1312 // the base type might be a dependent TemplateSpecializationType, or a
1313 // TemplateTypeParmType. If that happens, simply ignore it.
1314 // FIXME: If we want to support export, we probably need to add the
1315 // namespace of the template in a TemplateSpecializationType, or even
1316 // the classes and namespaces of known non-dependent arguments.
1317 if (!BaseType)
1318 continue;
Douglas Gregorfa047642009-02-04 00:32:51 +00001319 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1320 if (AssociatedClasses.insert(BaseDecl)) {
1321 // Find the associated namespace for this base class.
1322 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1323 while (BaseCtx->isRecord())
1324 BaseCtx = BaseCtx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001325 CollectNamespace(AssociatedNamespaces, BaseCtx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001326
1327 // Make sure we visit the bases of this base class.
1328 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1329 Bases.push_back(BaseDecl);
1330 }
1331 }
1332 }
1333}
1334
1335// \brief Add the associated classes and namespaces for
1336// argument-dependent lookup with an argument of type T
Mike Stump1eb44332009-09-09 15:08:12 +00001337// (C++ [basic.lookup.koenig]p2).
1338static void
1339addAssociatedClassesAndNamespaces(QualType T,
Douglas Gregorfa047642009-02-04 00:32:51 +00001340 ASTContext &Context,
1341 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001342 Sema::AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001343 // C++ [basic.lookup.koenig]p2:
1344 //
1345 // For each argument type T in the function call, there is a set
1346 // of zero or more associated namespaces and a set of zero or more
1347 // associated classes to be considered. The sets of namespaces and
1348 // classes is determined entirely by the types of the function
1349 // arguments (and the namespace of any template template
1350 // argument). Typedef names and using-declarations used to specify
1351 // the types do not contribute to this set. The sets of namespaces
1352 // and classes are determined in the following way:
1353 T = Context.getCanonicalType(T).getUnqualifiedType();
1354
1355 // -- If T is a pointer to U or an array of U, its associated
Mike Stump1eb44332009-09-09 15:08:12 +00001356 // namespaces and classes are those associated with U.
Douglas Gregorfa047642009-02-04 00:32:51 +00001357 //
1358 // We handle this by unwrapping pointer and array types immediately,
1359 // to avoid unnecessary recursion.
1360 while (true) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001361 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001362 T = Ptr->getPointeeType();
1363 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1364 T = Ptr->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001365 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001366 break;
1367 }
1368
1369 // -- If T is a fundamental type, its associated sets of
1370 // namespaces and classes are both empty.
John McCall183700f2009-09-21 23:43:11 +00001371 if (T->getAs<BuiltinType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001372 return;
1373
1374 // -- If T is a class type (including unions), its associated
1375 // classes are: the class itself; the class of which it is a
1376 // member, if any; and its direct and indirect base
1377 // classes. Its associated namespaces are the namespaces in
Mike Stump1eb44332009-09-09 15:08:12 +00001378 // which its associated classes are defined.
Ted Kremenek6217b802009-07-29 21:53:49 +00001379 if (const RecordType *ClassType = T->getAs<RecordType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001380 if (CXXRecordDecl *ClassDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001381 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001382 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1383 AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001384 AssociatedClasses);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001385 return;
1386 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001387
1388 // -- If T is an enumeration type, its associated namespace is
1389 // the namespace in which it is defined. If it is class
1390 // member, its associated class is the member’s class; else
Mike Stump1eb44332009-09-09 15:08:12 +00001391 // it has no associated class.
John McCall183700f2009-09-21 23:43:11 +00001392 if (const EnumType *EnumT = T->getAs<EnumType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001393 EnumDecl *Enum = EnumT->getDecl();
1394
1395 DeclContext *Ctx = Enum->getDeclContext();
1396 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1397 AssociatedClasses.insert(EnclosingClass);
1398
1399 // Add the associated namespace for this class.
1400 while (Ctx->isRecord())
1401 Ctx = Ctx->getParent();
John McCall6ff07852009-08-07 22:18:02 +00001402 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001403
1404 return;
1405 }
1406
1407 // -- If T is a function type, its associated namespaces and
1408 // classes are those associated with the function parameter
1409 // types and those associated with the return type.
John McCall183700f2009-09-21 23:43:11 +00001410 if (const FunctionType *FnType = T->getAs<FunctionType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001411 // Return type
John McCall183700f2009-09-21 23:43:11 +00001412 addAssociatedClassesAndNamespaces(FnType->getResultType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001413 Context,
John McCall6ff07852009-08-07 22:18:02 +00001414 AssociatedNamespaces, AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001415
John McCall183700f2009-09-21 23:43:11 +00001416 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001417 if (!Proto)
1418 return;
1419
1420 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001421 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001422 ArgEnd = Proto->arg_type_end();
Douglas Gregorfa047642009-02-04 00:32:51 +00001423 Arg != ArgEnd; ++Arg)
1424 addAssociatedClassesAndNamespaces(*Arg, Context,
John McCall6ff07852009-08-07 22:18:02 +00001425 AssociatedNamespaces, AssociatedClasses);
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Douglas Gregorfa047642009-02-04 00:32:51 +00001427 return;
1428 }
1429
1430 // -- If T is a pointer to a member function of a class X, its
1431 // associated namespaces and classes are those associated
1432 // with the function parameter types and return type,
Mike Stump1eb44332009-09-09 15:08:12 +00001433 // together with those associated with X.
Douglas Gregorfa047642009-02-04 00:32:51 +00001434 //
1435 // -- If T is a pointer to a data member of class X, its
1436 // associated namespaces and classes are those associated
1437 // with the member type together with those associated with
Mike Stump1eb44332009-09-09 15:08:12 +00001438 // X.
Ted Kremenek6217b802009-07-29 21:53:49 +00001439 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001440 // Handle the type that the pointer to member points to.
1441 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1442 Context,
John McCall6ff07852009-08-07 22:18:02 +00001443 AssociatedNamespaces,
1444 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001445
1446 // Handle the class type into which this points.
Ted Kremenek6217b802009-07-29 21:53:49 +00001447 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001448 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1449 Context,
John McCall6ff07852009-08-07 22:18:02 +00001450 AssociatedNamespaces,
1451 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001452
1453 return;
1454 }
1455
1456 // FIXME: What about block pointers?
1457 // FIXME: What about Objective-C message sends?
1458}
1459
1460/// \brief Find the associated classes and namespaces for
1461/// argument-dependent lookup for a call with the given set of
1462/// arguments.
1463///
1464/// This routine computes the sets of associated classes and associated
Mike Stump1eb44332009-09-09 15:08:12 +00001465/// namespaces searched by argument-dependent lookup
Douglas Gregorfa047642009-02-04 00:32:51 +00001466/// (C++ [basic.lookup.argdep]) for a given set of arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001467void
Douglas Gregorfa047642009-02-04 00:32:51 +00001468Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1469 AssociatedNamespaceSet &AssociatedNamespaces,
John McCall6ff07852009-08-07 22:18:02 +00001470 AssociatedClassSet &AssociatedClasses) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001471 AssociatedNamespaces.clear();
1472 AssociatedClasses.clear();
1473
1474 // C++ [basic.lookup.koenig]p2:
1475 // For each argument type T in the function call, there is a set
1476 // of zero or more associated namespaces and a set of zero or more
1477 // associated classes to be considered. The sets of namespaces and
1478 // classes is determined entirely by the types of the function
1479 // arguments (and the namespace of any template template
Mike Stump1eb44332009-09-09 15:08:12 +00001480 // argument).
Douglas Gregorfa047642009-02-04 00:32:51 +00001481 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1482 Expr *Arg = Args[ArgIdx];
1483
1484 if (Arg->getType() != Context.OverloadTy) {
1485 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001486 AssociatedNamespaces,
1487 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001488 continue;
1489 }
1490
1491 // [...] In addition, if the argument is the name or address of a
1492 // set of overloaded functions and/or function templates, its
1493 // associated classes and namespaces are the union of those
1494 // associated with each of the members of the set: the namespace
1495 // in which the function or function template is defined and the
1496 // classes and namespaces associated with its (non-dependent)
1497 // parameter types and return type.
Douglas Gregordaa439a2009-07-08 10:57:20 +00001498 Arg = Arg->IgnoreParens();
John McCallba135432009-11-21 08:51:07 +00001499 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
1500 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1501 Arg = unaryOp->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001502
John McCallba135432009-11-21 08:51:07 +00001503 // TODO: avoid the copies. This should be easy when the cases
1504 // share a storage implementation.
1505 llvm::SmallVector<NamedDecl*, 8> Functions;
1506
1507 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg))
1508 Functions.append(ULE->decls_begin(), ULE->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00001509 else
Douglas Gregorfa047642009-02-04 00:32:51 +00001510 continue;
1511
John McCallba135432009-11-21 08:51:07 +00001512 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Functions.begin(),
1513 E = Functions.end(); I != E; ++I) {
1514 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I);
Douglas Gregore53060f2009-06-25 22:08:12 +00001515 if (!FDecl)
John McCallba135432009-11-21 08:51:07 +00001516 FDecl = cast<FunctionTemplateDecl>(*I)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001517
1518 // Add the namespace in which this function was defined. Note
1519 // that, if this is a member function, we do *not* consider the
1520 // enclosing namespace of its class.
1521 DeclContext *Ctx = FDecl->getDeclContext();
John McCall6ff07852009-08-07 22:18:02 +00001522 CollectNamespace(AssociatedNamespaces, Ctx);
Douglas Gregorfa047642009-02-04 00:32:51 +00001523
1524 // Add the classes and namespaces associated with the parameter
1525 // types and return type of this function.
1526 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
John McCall6ff07852009-08-07 22:18:02 +00001527 AssociatedNamespaces,
1528 AssociatedClasses);
Douglas Gregorfa047642009-02-04 00:32:51 +00001529 }
1530 }
1531}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001532
1533/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1534/// an acceptable non-member overloaded operator for a call whose
1535/// arguments have types T1 (and, if non-empty, T2). This routine
1536/// implements the check in C++ [over.match.oper]p3b2 concerning
1537/// enumeration types.
Mike Stump1eb44332009-09-09 15:08:12 +00001538static bool
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001539IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1540 QualType T1, QualType T2,
1541 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001542 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1543 return true;
1544
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001545 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1546 return true;
1547
John McCall183700f2009-09-21 23:43:11 +00001548 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001549 if (Proto->getNumArgs() < 1)
1550 return false;
1551
1552 if (T1->isEnumeralType()) {
1553 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001554 if (Context.hasSameUnqualifiedType(T1, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001555 return true;
1556 }
1557
1558 if (Proto->getNumArgs() < 2)
1559 return false;
1560
1561 if (!T2.isNull() && T2->isEnumeralType()) {
1562 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
Douglas Gregora4923eb2009-11-16 21:35:15 +00001563 if (Context.hasSameUnqualifiedType(T2, ArgType))
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001564 return true;
1565 }
1566
1567 return false;
1568}
1569
John McCall7d384dd2009-11-18 07:57:50 +00001570NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
1571 LookupNameKind NameKind,
1572 RedeclarationKind Redecl) {
1573 LookupResult R(*this, Name, SourceLocation(), NameKind, Redecl);
1574 LookupName(R, S);
John McCall1bcee0a2009-12-02 08:25:40 +00001575 return R.getAsSingle<NamedDecl>();
John McCall7d384dd2009-11-18 07:57:50 +00001576}
1577
Douglas Gregor6e378de2009-04-23 23:18:26 +00001578/// \brief Find the protocol with the given name, if any.
1579ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
John McCallf36e02d2009-10-09 21:13:30 +00001580 Decl *D = LookupSingleName(TUScope, II, LookupObjCProtocolName);
Douglas Gregor6e378de2009-04-23 23:18:26 +00001581 return cast_or_null<ObjCProtocolDecl>(D);
1582}
1583
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001584/// \brief Find the Objective-C category implementation with the given
1585/// name, if any.
1586ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
John McCallf36e02d2009-10-09 21:13:30 +00001587 Decl *D = LookupSingleName(TUScope, II, LookupObjCCategoryImplName);
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001588 return cast_or_null<ObjCCategoryImplDecl>(D);
1589}
1590
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001591void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00001592 QualType T1, QualType T2,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001593 FunctionSet &Functions) {
1594 // C++ [over.match.oper]p3:
1595 // -- The set of non-member candidates is the result of the
1596 // unqualified lookup of operator@ in the context of the
1597 // expression according to the usual rules for name lookup in
1598 // unqualified function calls (3.4.2) except that all member
1599 // functions are ignored. However, if no operand has a class
1600 // type, only those non-member functions in the lookup set
Eli Friedman33a31382009-08-05 19:21:58 +00001601 // that have a first parameter of type T1 or "reference to
1602 // (possibly cv-qualified) T1", when T1 is an enumeration
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001603 // type, or (if there is a right operand) a second parameter
Eli Friedman33a31382009-08-05 19:21:58 +00001604 // of type T2 or "reference to (possibly cv-qualified) T2",
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001605 // when T2 is an enumeration type, are candidate functions.
1606 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
John McCalla24dc2e2009-11-17 02:14:36 +00001607 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
1608 LookupName(Operators, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001610 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1611
John McCallf36e02d2009-10-09 21:13:30 +00001612 if (Operators.empty())
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001613 return;
1614
1615 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1616 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001617 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001618 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1619 Functions.insert(FD); // FIXME: canonical FD
Mike Stump1eb44332009-09-09 15:08:12 +00001620 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor364e0212009-06-27 21:05:07 +00001621 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1622 // FIXME: friend operators?
Mike Stump1eb44332009-09-09 15:08:12 +00001623 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
Douglas Gregor364e0212009-06-27 21:05:07 +00001624 // later?
1625 if (!FunTmpl->getDeclContext()->isRecord())
1626 Functions.insert(FunTmpl);
1627 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001628 }
1629}
1630
John McCall6ff07852009-08-07 22:18:02 +00001631static void CollectFunctionDecl(Sema::FunctionSet &Functions,
1632 Decl *D) {
1633 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1634 Functions.insert(Func);
1635 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
1636 Functions.insert(FunTmpl);
1637}
1638
Sebastian Redl644be852009-10-23 19:23:15 +00001639void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001640 Expr **Args, unsigned NumArgs,
1641 FunctionSet &Functions) {
1642 // Find all of the associated namespaces and classes based on the
1643 // arguments we have.
1644 AssociatedNamespaceSet AssociatedNamespaces;
1645 AssociatedClassSet AssociatedClasses;
Mike Stump1eb44332009-09-09 15:08:12 +00001646 FindAssociatedClassesAndNamespaces(Args, NumArgs,
John McCall6ff07852009-08-07 22:18:02 +00001647 AssociatedNamespaces,
1648 AssociatedClasses);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001649
Sebastian Redl644be852009-10-23 19:23:15 +00001650 QualType T1, T2;
1651 if (Operator) {
1652 T1 = Args[0]->getType();
1653 if (NumArgs >= 2)
1654 T2 = Args[1]->getType();
1655 }
1656
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001657 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001658 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1659 // and let Y be the lookup set produced by argument dependent
1660 // lookup (defined as follows). If X contains [...] then Y is
1661 // empty. Otherwise Y is the set of declarations found in the
1662 // namespaces associated with the argument types as described
1663 // below. The set of declarations found by the lookup of the name
1664 // is the union of X and Y.
1665 //
1666 // Here, we compute Y and add its members to the overloaded
1667 // candidate set.
1668 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001669 NSEnd = AssociatedNamespaces.end();
1670 NS != NSEnd; ++NS) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001671 // When considering an associated namespace, the lookup is the
1672 // same as the lookup performed when the associated namespace is
1673 // used as a qualifier (3.4.3.2) except that:
1674 //
1675 // -- Any using-directives in the associated namespace are
1676 // ignored.
1677 //
John McCall6ff07852009-08-07 22:18:02 +00001678 // -- Any namespace-scope friend functions declared in
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001679 // associated classes are visible within their respective
1680 // namespaces even if they are not visible during an ordinary
1681 // lookup (11.4).
1682 DeclContext::lookup_iterator I, E;
John McCall3f9a8a62009-08-11 06:59:38 +00001683 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
John McCall6ff07852009-08-07 22:18:02 +00001684 Decl *D = *I;
John McCall02cace72009-08-28 07:59:38 +00001685 // If the only declaration here is an ordinary friend, consider
1686 // it only if it was declared in an associated classes.
1687 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00001688 DeclContext *LexDC = D->getLexicalDeclContext();
1689 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
1690 continue;
1691 }
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Sebastian Redl644be852009-10-23 19:23:15 +00001693 FunctionDecl *Fn;
1694 if (!Operator || !(Fn = dyn_cast<FunctionDecl>(D)) ||
1695 IsAcceptableNonMemberOperatorCandidate(Fn, T1, T2, Context))
1696 CollectFunctionDecl(Functions, D);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001697 }
1698 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001699}