SemaLookup.cpp revision 3eb207002be2bdffddc850aafd21a0a5710ca1c7
1//===--------------------- 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"
15#include "SemaInherit.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Basic/LangOptions.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include <set>
27#include <vector>
28#include <iterator>
29#include <utility>
30#include <algorithm>
31
32using namespace clang;
33
34typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
35typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
36typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
37
38/// UsingDirAncestorCompare - Implements strict weak ordering of
39/// UsingDirectives. It orders them by address of its common ancestor.
40struct UsingDirAncestorCompare {
41
42  /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
43  bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
44    return U->getCommonAncestor() < Ctx;
45  }
46
47  /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
48  bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
49    return Ctx < U->getCommonAncestor();
50  }
51
52  /// @brief Compares UsingDirectiveDecl common ancestors.
53  bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
54    return U1->getCommonAncestor() < U2->getCommonAncestor();
55  }
56};
57
58/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
59/// (ordered by common ancestors), found in namespace NS,
60/// including all found (recursively) in their nominated namespaces.
61void AddNamespaceUsingDirectives(ASTContext &Context,
62                                 DeclContext *NS,
63                                 UsingDirectivesTy &UDirs,
64                                 NamespaceSet &Visited) {
65  DeclContext::udir_iterator I, End;
66
67  for (llvm::tie(I, End) = NS->getUsingDirectives(Context); I !=End; ++I) {
68    UDirs.push_back(*I);
69    std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
70    NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
71    if (Visited.insert(Nominated).second)
72      AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited);
73  }
74}
75
76/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
77/// including all found in the namespaces they nominate.
78static void AddScopeUsingDirectives(ASTContext &Context, Scope *S,
79                                    UsingDirectivesTy &UDirs) {
80  NamespaceSet VisitedNS;
81
82  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
83
84    if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
85      VisitedNS.insert(NS);
86
87    AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS);
88
89  } else {
90    Scope::udir_iterator I = S->using_directives_begin(),
91                         End = S->using_directives_end();
92
93    for (; I != End; ++I) {
94      UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
95      UDirs.push_back(UD);
96      std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
97
98      NamespaceDecl *Nominated = UD->getNominatedNamespace();
99      if (!VisitedNS.count(Nominated)) {
100        VisitedNS.insert(Nominated);
101        AddNamespaceUsingDirectives(Context, Nominated, UDirs,
102                                    /*ref*/ VisitedNS);
103      }
104    }
105  }
106}
107
108/// MaybeConstructOverloadSet - Name lookup has determined that the
109/// elements in [I, IEnd) have the name that we are looking for, and
110/// *I is a match for the namespace. This routine returns an
111/// appropriate Decl for name lookup, which may either be *I or an
112/// OverloadedFunctionDecl that represents the overloaded functions in
113/// [I, IEnd).
114///
115/// The existance of this routine is temporary; users of LookupResult
116/// should be able to handle multiple results, to deal with cases of
117/// ambiguity and overloaded functions without needing to create a
118/// Decl node.
119template<typename DeclIterator>
120static NamedDecl *
121MaybeConstructOverloadSet(ASTContext &Context,
122                          DeclIterator I, DeclIterator IEnd) {
123  assert(I != IEnd && "Iterator range cannot be empty");
124  assert(!isa<OverloadedFunctionDecl>(*I) &&
125         "Cannot have an overloaded function");
126
127  if (isa<FunctionDecl>(*I)) {
128    // If we found a function, there might be more functions. If
129    // so, collect them into an overload set.
130    DeclIterator Last = I;
131    OverloadedFunctionDecl *Ovl = 0;
132    for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
133      if (!Ovl) {
134        // FIXME: We leak this overload set. Eventually, we want to
135        // stop building the declarations for these overload sets, so
136        // there will be nothing to leak.
137        Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
138                                             (*I)->getDeclName());
139        Ovl->addOverload(cast<FunctionDecl>(*I));
140      }
141      Ovl->addOverload(cast<FunctionDecl>(*Last));
142    }
143
144    // If we had more than one function, we built an overload
145    // set. Return it.
146    if (Ovl)
147      return Ovl;
148  }
149
150  return *I;
151}
152
153/// Merges together multiple LookupResults dealing with duplicated Decl's.
154static Sema::LookupResult
155MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
156  typedef Sema::LookupResult LResult;
157  typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
158
159  // Remove duplicated Decl pointing at same Decl, by storing them in
160  // associative collection. This might be case for code like:
161  //
162  //    namespace A { int i; }
163  //    namespace B { using namespace A; }
164  //    namespace C { using namespace A; }
165  //
166  //    void foo() {
167  //      using namespace B;
168  //      using namespace C;
169  //      ++i; // finds A::i, from both namespace B and C at global scope
170  //    }
171  //
172  //  C++ [namespace.qual].p3:
173  //    The same declaration found more than once is not an ambiguity
174  //    (because it is still a unique declaration).
175  DeclsSetTy FoundDecls;
176
177  // Counter of tag names, and functions for resolving ambiguity
178  // and name hiding.
179  std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
180
181  LookupResultsTy::iterator I = Results.begin(), End = Results.end();
182
183  // No name lookup results, return early.
184  if (I == End) return LResult::CreateLookupResult(Context, 0);
185
186  // Keep track of the tag declaration we found. We only use this if
187  // we find a single tag declaration.
188  TagDecl *TagFound = 0;
189
190  for (; I != End; ++I) {
191    switch (I->getKind()) {
192    case LResult::NotFound:
193      assert(false &&
194             "Should be always successful name lookup result here.");
195      break;
196
197    case LResult::AmbiguousReference:
198    case LResult::AmbiguousBaseSubobjectTypes:
199    case LResult::AmbiguousBaseSubobjects:
200      assert(false && "Shouldn't get ambiguous lookup here.");
201      break;
202
203    case LResult::Found: {
204      NamedDecl *ND = I->getAsDecl();
205      if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
206        TagFound = Context.getCanonicalDecl(TD);
207        TagNames += FoundDecls.insert(TagFound)?  1 : 0;
208      } else if (isa<FunctionDecl>(ND))
209        Functions += FoundDecls.insert(ND)? 1 : 0;
210      else
211        FoundDecls.insert(ND);
212      break;
213    }
214
215    case LResult::FoundOverloaded:
216      for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
217        Functions += FoundDecls.insert(*FI)? 1 : 0;
218      break;
219    }
220  }
221  OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
222  bool Ambiguous = false, NameHidesTags = false;
223
224  if (FoundDecls.size() == 1) {
225    // 1) Exactly one result.
226  } else if (TagNames > 1) {
227    // 2) Multiple tag names (even though they may be hidden by an
228    // object name).
229    Ambiguous = true;
230  } else if (FoundDecls.size() - TagNames == 1) {
231    // 3) Ordinary name hides (optional) tag.
232    NameHidesTags = TagFound;
233  } else if (Functions) {
234    // C++ [basic.lookup].p1:
235    // ... Name lookup may associate more than one declaration with
236    // a name if it finds the name to be a function name; the declarations
237    // are said to form a set of overloaded functions (13.1).
238    // Overload resolution (13.3) takes place after name lookup has succeeded.
239    //
240    if (!OrdinaryNonFunc) {
241      // 4) Functions hide tag names.
242      NameHidesTags = TagFound;
243    } else {
244      // 5) Functions + ordinary names.
245      Ambiguous = true;
246    }
247  } else {
248    // 6) Multiple non-tag names
249    Ambiguous = true;
250  }
251
252  if (Ambiguous)
253    return LResult::CreateLookupResult(Context,
254                                       FoundDecls.begin(), FoundDecls.size());
255  if (NameHidesTags) {
256    // There's only one tag, TagFound. Remove it.
257    assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
258    FoundDecls.erase(TagFound);
259  }
260
261  // Return successful name lookup result.
262  return LResult::CreateLookupResult(Context,
263                                MaybeConstructOverloadSet(Context,
264                                                          FoundDecls.begin(),
265                                                          FoundDecls.end()));
266}
267
268// Retrieve the set of identifier namespaces that correspond to a
269// specific kind of name lookup.
270inline unsigned
271getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
272                                          bool CPlusPlus) {
273  unsigned IDNS = 0;
274  switch (NameKind) {
275  case Sema::LookupOrdinaryName:
276  case Sema::LookupOperatorName:
277  case Sema::LookupRedeclarationWithLinkage:
278    IDNS = Decl::IDNS_Ordinary;
279    if (CPlusPlus)
280      IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
281    break;
282
283  case Sema::LookupTagName:
284    IDNS = Decl::IDNS_Tag;
285    break;
286
287  case Sema::LookupMemberName:
288    IDNS = Decl::IDNS_Member;
289    if (CPlusPlus)
290      IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
291    break;
292
293  case Sema::LookupNestedNameSpecifierName:
294  case Sema::LookupNamespaceName:
295    IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
296    break;
297
298  case Sema::LookupObjCProtocolName:
299    IDNS = Decl::IDNS_ObjCProtocol;
300    break;
301
302  case Sema::LookupObjCImplementationName:
303    IDNS = Decl::IDNS_ObjCImplementation;
304    break;
305
306  case Sema::LookupObjCCategoryImplName:
307    IDNS = Decl::IDNS_ObjCCategoryImpl;
308    break;
309  }
310  return IDNS;
311}
312
313Sema::LookupResult
314Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
315  if (ObjCCompatibleAliasDecl *Alias
316        = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
317    D = Alias->getClassInterface();
318
319  LookupResult Result;
320  Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
321    OverloadedDeclSingleDecl : SingleDecl;
322  Result.First = reinterpret_cast<uintptr_t>(D);
323  Result.Last = 0;
324  Result.Context = &Context;
325  return Result;
326}
327
328/// @brief Moves the name-lookup results from Other to this LookupResult.
329Sema::LookupResult
330Sema::LookupResult::CreateLookupResult(ASTContext &Context,
331                                       IdentifierResolver::iterator F,
332                                       IdentifierResolver::iterator L) {
333  LookupResult Result;
334  Result.Context = &Context;
335
336  if (F != L && isa<FunctionDecl>(*F)) {
337    IdentifierResolver::iterator Next = F;
338    ++Next;
339    if (Next != L && isa<FunctionDecl>(*Next)) {
340      Result.StoredKind = OverloadedDeclFromIdResolver;
341      Result.First = F.getAsOpaqueValue();
342      Result.Last = L.getAsOpaqueValue();
343      return Result;
344    }
345  }
346
347  Decl *D = *F;
348  if (ObjCCompatibleAliasDecl *Alias
349        = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
350    D = Alias->getClassInterface();
351
352  Result.StoredKind = SingleDecl;
353  Result.First = reinterpret_cast<uintptr_t>(D);
354  Result.Last = 0;
355  return Result;
356}
357
358Sema::LookupResult
359Sema::LookupResult::CreateLookupResult(ASTContext &Context,
360                                       DeclContext::lookup_iterator F,
361                                       DeclContext::lookup_iterator L) {
362  LookupResult Result;
363  Result.Context = &Context;
364
365  if (F != L && isa<FunctionDecl>(*F)) {
366    DeclContext::lookup_iterator Next = F;
367    ++Next;
368    if (Next != L && isa<FunctionDecl>(*Next)) {
369      Result.StoredKind = OverloadedDeclFromDeclContext;
370      Result.First = reinterpret_cast<uintptr_t>(F);
371      Result.Last = reinterpret_cast<uintptr_t>(L);
372      return Result;
373    }
374  }
375
376  Decl *D = *F;
377  if (ObjCCompatibleAliasDecl *Alias
378        = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
379    D = Alias->getClassInterface();
380
381  Result.StoredKind = SingleDecl;
382  Result.First = reinterpret_cast<uintptr_t>(D);
383  Result.Last = 0;
384  return Result;
385}
386
387/// @brief Determine the result of name lookup.
388Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
389  switch (StoredKind) {
390  case SingleDecl:
391    return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
392
393  case OverloadedDeclSingleDecl:
394  case OverloadedDeclFromIdResolver:
395  case OverloadedDeclFromDeclContext:
396    return FoundOverloaded;
397
398  case AmbiguousLookupStoresBasePaths:
399    return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
400
401  case AmbiguousLookupStoresDecls:
402    return AmbiguousReference;
403  }
404
405  // We can't ever get here.
406  return NotFound;
407}
408
409/// @brief Converts the result of name lookup into a single (possible
410/// NULL) pointer to a declaration.
411///
412/// The resulting declaration will either be the declaration we found
413/// (if only a single declaration was found), an
414/// OverloadedFunctionDecl (if an overloaded function was found), or
415/// NULL (if no declaration was found). This conversion must not be
416/// used anywhere where name lookup could result in an ambiguity.
417///
418/// The OverloadedFunctionDecl conversion is meant as a stop-gap
419/// solution, since it causes the OverloadedFunctionDecl to be
420/// leaked. FIXME: Eventually, there will be a better way to iterate
421/// over the set of overloaded functions returned by name lookup.
422NamedDecl *Sema::LookupResult::getAsDecl() const {
423  switch (StoredKind) {
424  case SingleDecl:
425    return reinterpret_cast<NamedDecl *>(First);
426
427  case OverloadedDeclFromIdResolver:
428    return MaybeConstructOverloadSet(*Context,
429                         IdentifierResolver::iterator::getFromOpaqueValue(First),
430                         IdentifierResolver::iterator::getFromOpaqueValue(Last));
431
432  case OverloadedDeclFromDeclContext:
433    return MaybeConstructOverloadSet(*Context,
434                           reinterpret_cast<DeclContext::lookup_iterator>(First),
435                           reinterpret_cast<DeclContext::lookup_iterator>(Last));
436
437  case OverloadedDeclSingleDecl:
438    return reinterpret_cast<OverloadedFunctionDecl*>(First);
439
440  case AmbiguousLookupStoresDecls:
441  case AmbiguousLookupStoresBasePaths:
442    assert(false &&
443           "Name lookup returned an ambiguity that could not be handled");
444    break;
445  }
446
447  return 0;
448}
449
450/// @brief Retrieves the BasePaths structure describing an ambiguous
451/// name lookup, or null.
452BasePaths *Sema::LookupResult::getBasePaths() const {
453  if (StoredKind == AmbiguousLookupStoresBasePaths)
454      return reinterpret_cast<BasePaths *>(First);
455  return 0;
456}
457
458Sema::LookupResult::iterator::reference
459Sema::LookupResult::iterator::operator*() const {
460  switch (Result->StoredKind) {
461  case SingleDecl:
462    return reinterpret_cast<NamedDecl*>(Current);
463
464  case OverloadedDeclSingleDecl:
465    return *reinterpret_cast<NamedDecl**>(Current);
466
467  case OverloadedDeclFromIdResolver:
468    return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
469
470  case AmbiguousLookupStoresBasePaths:
471    if (Result->Last)
472      return *reinterpret_cast<NamedDecl**>(Current);
473
474    // Fall through to handle the DeclContext::lookup_iterator we're
475    // storing.
476
477  case OverloadedDeclFromDeclContext:
478  case AmbiguousLookupStoresDecls:
479    return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
480  }
481
482  return 0;
483}
484
485Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
486  switch (Result->StoredKind) {
487  case SingleDecl:
488    Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
489    break;
490
491  case OverloadedDeclSingleDecl: {
492    NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
493    ++I;
494    Current = reinterpret_cast<uintptr_t>(I);
495    break;
496  }
497
498  case OverloadedDeclFromIdResolver: {
499    IdentifierResolver::iterator I
500      = IdentifierResolver::iterator::getFromOpaqueValue(Current);
501    ++I;
502    Current = I.getAsOpaqueValue();
503    break;
504  }
505
506  case AmbiguousLookupStoresBasePaths:
507    if (Result->Last) {
508      NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
509      ++I;
510      Current = reinterpret_cast<uintptr_t>(I);
511      break;
512    }
513    // Fall through to handle the DeclContext::lookup_iterator we're
514    // storing.
515
516  case OverloadedDeclFromDeclContext:
517  case AmbiguousLookupStoresDecls: {
518    DeclContext::lookup_iterator I
519      = reinterpret_cast<DeclContext::lookup_iterator>(Current);
520    ++I;
521    Current = reinterpret_cast<uintptr_t>(I);
522    break;
523  }
524  }
525
526  return *this;
527}
528
529Sema::LookupResult::iterator Sema::LookupResult::begin() {
530  switch (StoredKind) {
531  case SingleDecl:
532  case OverloadedDeclFromIdResolver:
533  case OverloadedDeclFromDeclContext:
534  case AmbiguousLookupStoresDecls:
535    return iterator(this, First);
536
537  case OverloadedDeclSingleDecl: {
538    OverloadedFunctionDecl * Ovl =
539      reinterpret_cast<OverloadedFunctionDecl*>(First);
540    return iterator(this,
541                    reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
542  }
543
544  case AmbiguousLookupStoresBasePaths:
545    if (Last)
546      return iterator(this,
547              reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
548    else
549      return iterator(this,
550              reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
551  }
552
553  // Required to suppress GCC warning.
554  return iterator();
555}
556
557Sema::LookupResult::iterator Sema::LookupResult::end() {
558  switch (StoredKind) {
559  case SingleDecl:
560  case OverloadedDeclFromIdResolver:
561  case OverloadedDeclFromDeclContext:
562  case AmbiguousLookupStoresDecls:
563    return iterator(this, Last);
564
565  case OverloadedDeclSingleDecl: {
566    OverloadedFunctionDecl * Ovl =
567      reinterpret_cast<OverloadedFunctionDecl*>(First);
568    return iterator(this,
569                    reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
570  }
571
572  case AmbiguousLookupStoresBasePaths:
573    if (Last)
574      return iterator(this,
575               reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
576    else
577      return iterator(this, reinterpret_cast<uintptr_t>(
578                                     getBasePaths()->front().Decls.second));
579  }
580
581  // Required to suppress GCC warning.
582  return iterator();
583}
584
585void Sema::LookupResult::Destroy() {
586  if (BasePaths *Paths = getBasePaths())
587    delete Paths;
588  else if (getKind() == AmbiguousReference)
589    delete[] reinterpret_cast<NamedDecl **>(First);
590}
591
592static void
593CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
594                   DeclarationName Name, Sema::LookupNameKind NameKind,
595                   unsigned IDNS, LookupResultsTy &Results,
596                   UsingDirectivesTy *UDirs = 0) {
597
598  assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
599
600  // Perform qualified name lookup into the LookupCtx.
601  DeclContext::lookup_iterator I, E;
602  for (llvm::tie(I, E) = NS->lookup(Context, Name); I != E; ++I)
603    if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
604      Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
605      break;
606    }
607
608  if (UDirs) {
609    // For each UsingDirectiveDecl, which common ancestor is equal
610    // to NS, we preform qualified name lookup into namespace nominated by it.
611    UsingDirectivesTy::const_iterator UI, UEnd;
612    llvm::tie(UI, UEnd) =
613      std::equal_range(UDirs->begin(), UDirs->end(), NS,
614                       UsingDirAncestorCompare());
615
616    for (; UI != UEnd; ++UI)
617      CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
618                         Name, NameKind, IDNS, Results);
619  }
620}
621
622static bool isNamespaceOrTranslationUnitScope(Scope *S) {
623  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
624    return Ctx->isFileContext();
625  return false;
626}
627
628std::pair<bool, Sema::LookupResult>
629Sema::CppLookupName(Scope *S, DeclarationName Name,
630                    LookupNameKind NameKind, bool RedeclarationOnly) {
631  assert(getLangOptions().CPlusPlus &&
632         "Can perform only C++ lookup");
633  unsigned IDNS
634    = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
635  Scope *Initial = S;
636  DeclContext *OutOfLineCtx = 0;
637  IdentifierResolver::iterator
638    I = IdResolver.begin(Name),
639    IEnd = IdResolver.end();
640
641  // First we lookup local scope.
642  // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
643  // ...During unqualified name lookup (3.4.1), the names appear as if
644  // they were declared in the nearest enclosing namespace which contains
645  // both the using-directive and the nominated namespace.
646  // [Note: in this context, “contains” means “contains directly or
647  // indirectly”.
648  //
649  // For example:
650  // namespace A { int i; }
651  // void foo() {
652  //   int i;
653  //   {
654  //     using namespace A;
655  //     ++i; // finds local 'i', A::i appears at global scope
656  //   }
657  // }
658  //
659  for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
660    // Check whether the IdResolver has anything in this scope.
661    for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
662      if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
663        // We found something.  Look for anything else in our scope
664        // with this same name and in an acceptable identifier
665        // namespace, so that we can construct an overload set if we
666        // need to.
667        IdentifierResolver::iterator LastI = I;
668        for (++LastI; LastI != IEnd; ++LastI) {
669          if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
670            break;
671        }
672        LookupResult Result =
673          LookupResult::CreateLookupResult(Context, I, LastI);
674        return std::make_pair(true, Result);
675      }
676    }
677    if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
678      LookupResult R;
679      // Perform member lookup into struct.
680      // FIXME: In some cases, we know that every name that could be
681      // found by this qualified name lookup will also be on the
682      // identifier chain. For example, inside a class without any
683      // base classes, we never need to perform qualified lookup
684      // because all of the members are on top of the identifier
685      // chain.
686      if (isa<RecordDecl>(Ctx)) {
687        R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
688        if (R || RedeclarationOnly)
689          return std::make_pair(true, R);
690      }
691      if (Ctx->getParent() != Ctx->getLexicalParent()) {
692        // It is out of line defined C++ method or struct, we continue
693        // doing name lookup in parent context. Once we will find namespace
694        // or translation-unit we save it for possible checking
695        // using-directives later.
696        for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
697             OutOfLineCtx = OutOfLineCtx->getParent()) {
698          R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
699          if (R || RedeclarationOnly)
700            return std::make_pair(true, R);
701        }
702      }
703    }
704  }
705
706  // Collect UsingDirectiveDecls in all scopes, and recursively all
707  // nominated namespaces by those using-directives.
708  // UsingDirectives are pushed to heap, in common ancestor pointer
709  // value order.
710  // FIXME: Cache this sorted list in Scope structure, and DeclContext,
711  // so we don't build it for each lookup!
712  UsingDirectivesTy UDirs;
713  for (Scope *SC = Initial; SC; SC = SC->getParent())
714    if (SC->getFlags() & Scope::DeclScope)
715      AddScopeUsingDirectives(Context, SC, UDirs);
716
717  // Sort heapified UsingDirectiveDecls.
718  std::sort_heap(UDirs.begin(), UDirs.end());
719
720  // Lookup namespace scope, and global scope.
721  // Unqualified name lookup in C++ requires looking into scopes
722  // that aren't strictly lexical, and therefore we walk through the
723  // context as well as walking through the scopes.
724
725  LookupResultsTy LookupResults;
726  assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
727         "We should have been looking only at file context here already.");
728  bool LookedInCtx = false;
729  LookupResult Result;
730  while (OutOfLineCtx &&
731         OutOfLineCtx != S->getEntity() &&
732         OutOfLineCtx->isNamespace()) {
733    LookedInCtx = true;
734
735    // Look into context considering using-directives.
736    CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
737                       LookupResults, &UDirs);
738
739    if ((Result = MergeLookupResults(Context, LookupResults)) ||
740        (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
741      return std::make_pair(true, Result);
742
743    OutOfLineCtx = OutOfLineCtx->getParent();
744  }
745
746  for (; S; S = S->getParent()) {
747    DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
748    assert(Ctx && Ctx->isFileContext() &&
749           "We should have been looking only at file context here already.");
750
751    // Check whether the IdResolver has anything in this scope.
752    for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
753      if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
754        // We found something.  Look for anything else in our scope
755        // with this same name and in an acceptable identifier
756        // namespace, so that we can construct an overload set if we
757        // need to.
758        IdentifierResolver::iterator LastI = I;
759        for (++LastI; LastI != IEnd; ++LastI) {
760          if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
761            break;
762        }
763
764        // We store name lookup result, and continue trying to look into
765        // associated context, and maybe namespaces nominated by
766        // using-directives.
767        LookupResults.push_back(
768          LookupResult::CreateLookupResult(Context, I, LastI));
769        break;
770      }
771    }
772
773    LookedInCtx = true;
774    // Look into context considering using-directives.
775    CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
776                       LookupResults, &UDirs);
777
778    if ((Result = MergeLookupResults(Context, LookupResults)) ||
779        (RedeclarationOnly && !Ctx->isTransparentContext()))
780      return std::make_pair(true, Result);
781  }
782
783  if (!(LookedInCtx || LookupResults.empty())) {
784    // We didn't Performed lookup in Scope entity, so we return
785    // result form IdentifierResolver.
786    assert((LookupResults.size() == 1) && "Wrong size!");
787    return std::make_pair(true, LookupResults.front());
788  }
789  return std::make_pair(false, LookupResult());
790}
791
792/// @brief Perform unqualified name lookup starting from a given
793/// scope.
794///
795/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
796/// used to find names within the current scope. For example, 'x' in
797/// @code
798/// int x;
799/// int f() {
800///   return x; // unqualified name look finds 'x' in the global scope
801/// }
802/// @endcode
803///
804/// Different lookup criteria can find different names. For example, a
805/// particular scope can have both a struct and a function of the same
806/// name, and each can be found by certain lookup criteria. For more
807/// information about lookup criteria, see the documentation for the
808/// class LookupCriteria.
809///
810/// @param S        The scope from which unqualified name lookup will
811/// begin. If the lookup criteria permits, name lookup may also search
812/// in the parent scopes.
813///
814/// @param Name     The name of the entity that we are searching for.
815///
816/// @param Loc      If provided, the source location where we're performing
817/// name lookup. At present, this is only used to produce diagnostics when
818/// C library functions (like "malloc") are implicitly declared.
819///
820/// @returns The result of name lookup, which includes zero or more
821/// declarations and possibly additional information used to diagnose
822/// ambiguities.
823Sema::LookupResult
824Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
825                 bool RedeclarationOnly, bool AllowBuiltinCreation,
826                 SourceLocation Loc) {
827  if (!Name) return LookupResult::CreateLookupResult(Context, 0);
828
829  if (!getLangOptions().CPlusPlus) {
830    // Unqualified name lookup in C/Objective-C is purely lexical, so
831    // search in the declarations attached to the name.
832    unsigned IDNS = 0;
833    switch (NameKind) {
834    case Sema::LookupOrdinaryName:
835      IDNS = Decl::IDNS_Ordinary;
836      break;
837
838    case Sema::LookupTagName:
839      IDNS = Decl::IDNS_Tag;
840      break;
841
842    case Sema::LookupMemberName:
843      IDNS = Decl::IDNS_Member;
844      break;
845
846    case Sema::LookupOperatorName:
847    case Sema::LookupNestedNameSpecifierName:
848    case Sema::LookupNamespaceName:
849      assert(false && "C does not perform these kinds of name lookup");
850      break;
851
852    case Sema::LookupRedeclarationWithLinkage:
853      // Find the nearest non-transparent declaration scope.
854      while (!(S->getFlags() & Scope::DeclScope) ||
855             (S->getEntity() &&
856              static_cast<DeclContext *>(S->getEntity())
857                ->isTransparentContext()))
858        S = S->getParent();
859      IDNS = Decl::IDNS_Ordinary;
860      break;
861
862    case Sema::LookupObjCProtocolName:
863      IDNS = Decl::IDNS_ObjCProtocol;
864      break;
865
866    case Sema::LookupObjCImplementationName:
867      IDNS = Decl::IDNS_ObjCImplementation;
868      break;
869
870    case Sema::LookupObjCCategoryImplName:
871      IDNS = Decl::IDNS_ObjCCategoryImpl;
872      break;
873    }
874
875    // Scan up the scope chain looking for a decl that matches this
876    // identifier that is in the appropriate namespace.  This search
877    // should not take long, as shadowing of names is uncommon, and
878    // deep shadowing is extremely uncommon.
879    bool LeftStartingScope = false;
880
881    for (IdentifierResolver::iterator I = IdResolver.begin(Name),
882                                   IEnd = IdResolver.end();
883         I != IEnd; ++I)
884      if ((*I)->isInIdentifierNamespace(IDNS)) {
885        if (NameKind == LookupRedeclarationWithLinkage) {
886          // Determine whether this (or a previous) declaration is
887          // out-of-scope.
888          if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
889            LeftStartingScope = true;
890
891          // If we found something outside of our starting scope that
892          // does not have linkage, skip it.
893          if (LeftStartingScope && !((*I)->hasLinkage()))
894            continue;
895        }
896
897        if ((*I)->getAttr<OverloadableAttr>()) {
898          // If this declaration has the "overloadable" attribute, we
899          // might have a set of overloaded functions.
900
901          // Figure out what scope the identifier is in.
902          while (!(S->getFlags() & Scope::DeclScope) ||
903                 !S->isDeclScope(DeclPtrTy::make(*I)))
904            S = S->getParent();
905
906          // Find the last declaration in this scope (with the same
907          // name, naturally).
908          IdentifierResolver::iterator LastI = I;
909          for (++LastI; LastI != IEnd; ++LastI) {
910            if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
911              break;
912          }
913
914          return LookupResult::CreateLookupResult(Context, I, LastI);
915        }
916
917        // We have a single lookup result.
918        return LookupResult::CreateLookupResult(Context, *I);
919      }
920  } else {
921    // Perform C++ unqualified name lookup.
922    std::pair<bool, LookupResult> MaybeResult =
923      CppLookupName(S, Name, NameKind, RedeclarationOnly);
924    if (MaybeResult.first)
925      return MaybeResult.second;
926  }
927
928  // If we didn't find a use of this identifier, and if the identifier
929  // corresponds to a compiler builtin, create the decl object for the builtin
930  // now, injecting it into translation unit scope, and return it.
931  if (NameKind == LookupOrdinaryName ||
932      NameKind == LookupRedeclarationWithLinkage) {
933    IdentifierInfo *II = Name.getAsIdentifierInfo();
934    if (II && AllowBuiltinCreation) {
935      // If this is a builtin on this (or all) targets, create the decl.
936      if (unsigned BuiltinID = II->getBuiltinID()) {
937        // In C++, we don't have any predefined library functions like
938        // 'malloc'. Instead, we'll just error.
939        if (getLangOptions().CPlusPlus &&
940            Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
941          return LookupResult::CreateLookupResult(Context, 0);
942
943        return LookupResult::CreateLookupResult(Context,
944                            LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
945                                                S, RedeclarationOnly, Loc));
946      }
947    }
948  }
949  return LookupResult::CreateLookupResult(Context, 0);
950}
951
952/// @brief Perform qualified name lookup into a given context.
953///
954/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
955/// names when the context of those names is explicit specified, e.g.,
956/// "std::vector" or "x->member".
957///
958/// Different lookup criteria can find different names. For example, a
959/// particular scope can have both a struct and a function of the same
960/// name, and each can be found by certain lookup criteria. For more
961/// information about lookup criteria, see the documentation for the
962/// class LookupCriteria.
963///
964/// @param LookupCtx The context in which qualified name lookup will
965/// search. If the lookup criteria permits, name lookup may also search
966/// in the parent contexts or (for C++ classes) base classes.
967///
968/// @param Name     The name of the entity that we are searching for.
969///
970/// @param Criteria The criteria that this routine will use to
971/// determine which names are visible and which names will be
972/// found. Note that name lookup will find a name that is visible by
973/// the given criteria, but the entity itself may not be semantically
974/// correct or even the kind of entity expected based on the
975/// lookup. For example, searching for a nested-name-specifier name
976/// might result in an EnumDecl, which is visible but is not permitted
977/// as a nested-name-specifier in C++03.
978///
979/// @returns The result of name lookup, which includes zero or more
980/// declarations and possibly additional information used to diagnose
981/// ambiguities.
982Sema::LookupResult
983Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
984                          LookupNameKind NameKind, bool RedeclarationOnly) {
985  assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
986
987  if (!Name) return LookupResult::CreateLookupResult(Context, 0);
988
989  // If we're performing qualified name lookup (e.g., lookup into a
990  // struct), find fields as part of ordinary name lookup.
991  unsigned IDNS
992    = getIdentifierNamespacesFromLookupNameKind(NameKind,
993                                                getLangOptions().CPlusPlus);
994  if (NameKind == LookupOrdinaryName)
995    IDNS |= Decl::IDNS_Member;
996
997  // Perform qualified name lookup into the LookupCtx.
998  DeclContext::lookup_iterator I, E;
999  for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
1000    if (isAcceptableLookupResult(*I, NameKind, IDNS))
1001      return LookupResult::CreateLookupResult(Context, I, E);
1002
1003  // If this isn't a C++ class or we aren't allowed to look into base
1004  // classes, we're done.
1005  if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
1006    return LookupResult::CreateLookupResult(Context, 0);
1007
1008  // Perform lookup into our base classes.
1009  BasePaths Paths;
1010  Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
1011
1012  // Look for this member in our base classes
1013  if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
1014                     MemberLookupCriteria(Name, NameKind, IDNS), Paths))
1015    return LookupResult::CreateLookupResult(Context, 0);
1016
1017  // C++ [class.member.lookup]p2:
1018  //   [...] If the resulting set of declarations are not all from
1019  //   sub-objects of the same type, or the set has a nonstatic member
1020  //   and includes members from distinct sub-objects, there is an
1021  //   ambiguity and the program is ill-formed. Otherwise that set is
1022  //   the result of the lookup.
1023  // FIXME: support using declarations!
1024  QualType SubobjectType;
1025  int SubobjectNumber = 0;
1026  for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1027       Path != PathEnd; ++Path) {
1028    const BasePathElement &PathElement = Path->back();
1029
1030    // Determine whether we're looking at a distinct sub-object or not.
1031    if (SubobjectType.isNull()) {
1032      // This is the first subobject we've looked at. Record it's type.
1033      SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1034      SubobjectNumber = PathElement.SubobjectNumber;
1035    } else if (SubobjectType
1036                 != Context.getCanonicalType(PathElement.Base->getType())) {
1037      // We found members of the given name in two subobjects of
1038      // different types. This lookup is ambiguous.
1039      BasePaths *PathsOnHeap = new BasePaths;
1040      PathsOnHeap->swap(Paths);
1041      return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
1042    } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1043      // We have a different subobject of the same type.
1044
1045      // C++ [class.member.lookup]p5:
1046      //   A static member, a nested type or an enumerator defined in
1047      //   a base class T can unambiguously be found even if an object
1048      //   has more than one base class subobject of type T.
1049      Decl *FirstDecl = *Path->Decls.first;
1050      if (isa<VarDecl>(FirstDecl) ||
1051          isa<TypeDecl>(FirstDecl) ||
1052          isa<EnumConstantDecl>(FirstDecl))
1053        continue;
1054
1055      if (isa<CXXMethodDecl>(FirstDecl)) {
1056        // Determine whether all of the methods are static.
1057        bool AllMethodsAreStatic = true;
1058        for (DeclContext::lookup_iterator Func = Path->Decls.first;
1059             Func != Path->Decls.second; ++Func) {
1060          if (!isa<CXXMethodDecl>(*Func)) {
1061            assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1062            break;
1063          }
1064
1065          if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1066            AllMethodsAreStatic = false;
1067            break;
1068          }
1069        }
1070
1071        if (AllMethodsAreStatic)
1072          continue;
1073      }
1074
1075      // We have found a nonstatic member name in multiple, distinct
1076      // subobjects. Name lookup is ambiguous.
1077      BasePaths *PathsOnHeap = new BasePaths;
1078      PathsOnHeap->swap(Paths);
1079      return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
1080    }
1081  }
1082
1083  // Lookup in a base class succeeded; return these results.
1084
1085  // If we found a function declaration, return an overload set.
1086  if (isa<FunctionDecl>(*Paths.front().Decls.first))
1087    return LookupResult::CreateLookupResult(Context,
1088                        Paths.front().Decls.first, Paths.front().Decls.second);
1089
1090  // We found a non-function declaration; return a single declaration.
1091  return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
1092}
1093
1094/// @brief Performs name lookup for a name that was parsed in the
1095/// source code, and may contain a C++ scope specifier.
1096///
1097/// This routine is a convenience routine meant to be called from
1098/// contexts that receive a name and an optional C++ scope specifier
1099/// (e.g., "N::M::x"). It will then perform either qualified or
1100/// unqualified name lookup (with LookupQualifiedName or LookupName,
1101/// respectively) on the given name and return those results.
1102///
1103/// @param S        The scope from which unqualified name lookup will
1104/// begin.
1105///
1106/// @param SS       An optional C++ scope-specified, e.g., "::N::M".
1107///
1108/// @param Name     The name of the entity that name lookup will
1109/// search for.
1110///
1111/// @param Loc      If provided, the source location where we're performing
1112/// name lookup. At present, this is only used to produce diagnostics when
1113/// C library functions (like "malloc") are implicitly declared.
1114///
1115/// @returns The result of qualified or unqualified name lookup.
1116Sema::LookupResult
1117Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1118                       DeclarationName Name, LookupNameKind NameKind,
1119                       bool RedeclarationOnly, bool AllowBuiltinCreation,
1120                       SourceLocation Loc) {
1121  if (SS && (SS->isSet() || SS->isInvalid())) {
1122    // If the scope specifier is invalid, don't even look for
1123    // anything.
1124    if (SS->isInvalid())
1125      return LookupResult::CreateLookupResult(Context, 0);
1126
1127    assert(!isUnknownSpecialization(*SS) && "Can't lookup dependent types");
1128
1129    if (isDependentScopeSpecifier(*SS)) {
1130      // Determine whether we are looking into the current
1131      // instantiation.
1132      NestedNameSpecifier *NNS
1133        = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1134      CXXRecordDecl *Current = getCurrentInstantiationOf(NNS);
1135      assert(Current && "Bad dependent scope specifier");
1136
1137      // We nested name specifier refers to the current instantiation,
1138      // so now we will look for a member of the current instantiation
1139      // (C++0x [temp.dep.type]).
1140      unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, true);
1141      DeclContext::lookup_iterator I, E;
1142      for (llvm::tie(I, E) = Current->lookup(Context, Name); I != E; ++I)
1143        if (isAcceptableLookupResult(*I, NameKind, IDNS))
1144          return LookupResult::CreateLookupResult(Context, I, E);
1145    }
1146
1147    if (RequireCompleteDeclContext(*SS))
1148      return LookupResult::CreateLookupResult(Context, 0);
1149
1150    return LookupQualifiedName(computeDeclContext(*SS),
1151                               Name, NameKind, RedeclarationOnly);
1152  }
1153
1154  return LookupName(S, Name, NameKind, RedeclarationOnly,
1155                    AllowBuiltinCreation, Loc);
1156}
1157
1158
1159/// @brief Produce a diagnostic describing the ambiguity that resulted
1160/// from name lookup.
1161///
1162/// @param Result       The ambiguous name lookup result.
1163///
1164/// @param Name         The name of the entity that name lookup was
1165/// searching for.
1166///
1167/// @param NameLoc      The location of the name within the source code.
1168///
1169/// @param LookupRange  A source range that provides more
1170/// source-location information concerning the lookup itself. For
1171/// example, this range might highlight a nested-name-specifier that
1172/// precedes the name.
1173///
1174/// @returns true
1175bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1176                                   SourceLocation NameLoc,
1177                                   SourceRange LookupRange) {
1178  assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1179
1180  if (BasePaths *Paths = Result.getBasePaths()) {
1181    if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1182      QualType SubobjectType = Paths->front().back().Base->getType();
1183      Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1184        << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1185        << LookupRange;
1186
1187      DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1188      while (isa<CXXMethodDecl>(*Found) &&
1189             cast<CXXMethodDecl>(*Found)->isStatic())
1190        ++Found;
1191
1192      Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1193
1194      Result.Destroy();
1195      return true;
1196    }
1197
1198    assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1199           "Unhandled form of name lookup ambiguity");
1200
1201    Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1202      << Name << LookupRange;
1203
1204    std::set<Decl *> DeclsPrinted;
1205    for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1206         Path != PathEnd; ++Path) {
1207      Decl *D = *Path->Decls.first;
1208      if (DeclsPrinted.insert(D).second)
1209        Diag(D->getLocation(), diag::note_ambiguous_member_found);
1210    }
1211
1212    Result.Destroy();
1213    return true;
1214  } else if (Result.getKind() == LookupResult::AmbiguousReference) {
1215    Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1216
1217    NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
1218            **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
1219
1220    for (; DI != DEnd; ++DI)
1221      Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1222
1223    Result.Destroy();
1224    return true;
1225  }
1226
1227  assert(false && "Unhandled form of name lookup ambiguity");
1228
1229  // We can't reach here.
1230  return true;
1231}
1232
1233// \brief Add the associated classes and namespaces for
1234// argument-dependent lookup with an argument of class type
1235// (C++ [basic.lookup.koenig]p2).
1236static void
1237addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1238                                  ASTContext &Context,
1239                            Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1240                            Sema::AssociatedClassSet &AssociatedClasses) {
1241  // C++ [basic.lookup.koenig]p2:
1242  //   [...]
1243  //     -- If T is a class type (including unions), its associated
1244  //        classes are: the class itself; the class of which it is a
1245  //        member, if any; and its direct and indirect base
1246  //        classes. Its associated namespaces are the namespaces in
1247  //        which its associated classes are defined.
1248
1249  // Add the class of which it is a member, if any.
1250  DeclContext *Ctx = Class->getDeclContext();
1251  if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1252    AssociatedClasses.insert(EnclosingClass);
1253
1254  // Add the associated namespace for this class.
1255  while (Ctx->isRecord())
1256    Ctx = Ctx->getParent();
1257  if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1258    AssociatedNamespaces.insert(EnclosingNamespace);
1259
1260  // Add the class itself. If we've already seen this class, we don't
1261  // need to visit base classes.
1262  if (!AssociatedClasses.insert(Class))
1263    return;
1264
1265  // FIXME: Handle class template specializations
1266
1267  // Add direct and indirect base classes along with their associated
1268  // namespaces.
1269  llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1270  Bases.push_back(Class);
1271  while (!Bases.empty()) {
1272    // Pop this class off the stack.
1273    Class = Bases.back();
1274    Bases.pop_back();
1275
1276    // Visit the base classes.
1277    for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1278                                         BaseEnd = Class->bases_end();
1279         Base != BaseEnd; ++Base) {
1280      const RecordType *BaseType = Base->getType()->getAsRecordType();
1281      CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1282      if (AssociatedClasses.insert(BaseDecl)) {
1283        // Find the associated namespace for this base class.
1284        DeclContext *BaseCtx = BaseDecl->getDeclContext();
1285        while (BaseCtx->isRecord())
1286          BaseCtx = BaseCtx->getParent();
1287        if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1288          AssociatedNamespaces.insert(EnclosingNamespace);
1289
1290        // Make sure we visit the bases of this base class.
1291        if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1292          Bases.push_back(BaseDecl);
1293      }
1294    }
1295  }
1296}
1297
1298// \brief Add the associated classes and namespaces for
1299// argument-dependent lookup with an argument of type T
1300// (C++ [basic.lookup.koenig]p2).
1301static void
1302addAssociatedClassesAndNamespaces(QualType T,
1303                                  ASTContext &Context,
1304                            Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1305                            Sema::AssociatedClassSet &AssociatedClasses) {
1306  // C++ [basic.lookup.koenig]p2:
1307  //
1308  //   For each argument type T in the function call, there is a set
1309  //   of zero or more associated namespaces and a set of zero or more
1310  //   associated classes to be considered. The sets of namespaces and
1311  //   classes is determined entirely by the types of the function
1312  //   arguments (and the namespace of any template template
1313  //   argument). Typedef names and using-declarations used to specify
1314  //   the types do not contribute to this set. The sets of namespaces
1315  //   and classes are determined in the following way:
1316  T = Context.getCanonicalType(T).getUnqualifiedType();
1317
1318  //    -- If T is a pointer to U or an array of U, its associated
1319  //       namespaces and classes are those associated with U.
1320  //
1321  // We handle this by unwrapping pointer and array types immediately,
1322  // to avoid unnecessary recursion.
1323  while (true) {
1324    if (const PointerType *Ptr = T->getAsPointerType())
1325      T = Ptr->getPointeeType();
1326    else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1327      T = Ptr->getElementType();
1328    else
1329      break;
1330  }
1331
1332  //     -- If T is a fundamental type, its associated sets of
1333  //        namespaces and classes are both empty.
1334  if (T->getAsBuiltinType())
1335    return;
1336
1337  //     -- If T is a class type (including unions), its associated
1338  //        classes are: the class itself; the class of which it is a
1339  //        member, if any; and its direct and indirect base
1340  //        classes. Its associated namespaces are the namespaces in
1341  //        which its associated classes are defined.
1342  if (const RecordType *ClassType = T->getAsRecordType())
1343    if (CXXRecordDecl *ClassDecl
1344        = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1345      addAssociatedClassesAndNamespaces(ClassDecl, Context,
1346                                        AssociatedNamespaces,
1347                                        AssociatedClasses);
1348      return;
1349    }
1350
1351  //     -- If T is an enumeration type, its associated namespace is
1352  //        the namespace in which it is defined. If it is class
1353  //        member, its associated class is the member’s class; else
1354  //        it has no associated class.
1355  if (const EnumType *EnumT = T->getAsEnumType()) {
1356    EnumDecl *Enum = EnumT->getDecl();
1357
1358    DeclContext *Ctx = Enum->getDeclContext();
1359    if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1360      AssociatedClasses.insert(EnclosingClass);
1361
1362    // Add the associated namespace for this class.
1363    while (Ctx->isRecord())
1364      Ctx = Ctx->getParent();
1365    if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1366      AssociatedNamespaces.insert(EnclosingNamespace);
1367
1368    return;
1369  }
1370
1371  //     -- If T is a function type, its associated namespaces and
1372  //        classes are those associated with the function parameter
1373  //        types and those associated with the return type.
1374  if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1375    // Return type
1376    addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1377                                      Context,
1378                                      AssociatedNamespaces, AssociatedClasses);
1379
1380    const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
1381    if (!Proto)
1382      return;
1383
1384    // Argument types
1385    for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1386                                           ArgEnd = Proto->arg_type_end();
1387         Arg != ArgEnd; ++Arg)
1388      addAssociatedClassesAndNamespaces(*Arg, Context,
1389                                        AssociatedNamespaces, AssociatedClasses);
1390
1391    return;
1392  }
1393
1394  //     -- If T is a pointer to a member function of a class X, its
1395  //        associated namespaces and classes are those associated
1396  //        with the function parameter types and return type,
1397  //        together with those associated with X.
1398  //
1399  //     -- If T is a pointer to a data member of class X, its
1400  //        associated namespaces and classes are those associated
1401  //        with the member type together with those associated with
1402  //        X.
1403  if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1404    // Handle the type that the pointer to member points to.
1405    addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1406                                      Context,
1407                                      AssociatedNamespaces, AssociatedClasses);
1408
1409    // Handle the class type into which this points.
1410    if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1411      addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1412                                        Context,
1413                                        AssociatedNamespaces, AssociatedClasses);
1414
1415    return;
1416  }
1417
1418  // FIXME: What about block pointers?
1419  // FIXME: What about Objective-C message sends?
1420}
1421
1422/// \brief Find the associated classes and namespaces for
1423/// argument-dependent lookup for a call with the given set of
1424/// arguments.
1425///
1426/// This routine computes the sets of associated classes and associated
1427/// namespaces searched by argument-dependent lookup
1428/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1429void
1430Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1431                                 AssociatedNamespaceSet &AssociatedNamespaces,
1432                                 AssociatedClassSet &AssociatedClasses) {
1433  AssociatedNamespaces.clear();
1434  AssociatedClasses.clear();
1435
1436  // C++ [basic.lookup.koenig]p2:
1437  //   For each argument type T in the function call, there is a set
1438  //   of zero or more associated namespaces and a set of zero or more
1439  //   associated classes to be considered. The sets of namespaces and
1440  //   classes is determined entirely by the types of the function
1441  //   arguments (and the namespace of any template template
1442  //   argument).
1443  for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1444    Expr *Arg = Args[ArgIdx];
1445
1446    if (Arg->getType() != Context.OverloadTy) {
1447      addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1448                                        AssociatedNamespaces, AssociatedClasses);
1449      continue;
1450    }
1451
1452    // [...] In addition, if the argument is the name or address of a
1453    // set of overloaded functions and/or function templates, its
1454    // associated classes and namespaces are the union of those
1455    // associated with each of the members of the set: the namespace
1456    // in which the function or function template is defined and the
1457    // classes and namespaces associated with its (non-dependent)
1458    // parameter types and return type.
1459    DeclRefExpr *DRE = 0;
1460    if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1461      if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1462        DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1463    } else
1464      DRE = dyn_cast<DeclRefExpr>(Arg);
1465    if (!DRE)
1466      continue;
1467
1468    OverloadedFunctionDecl *Ovl
1469      = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1470    if (!Ovl)
1471      continue;
1472
1473    for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1474                                                FuncEnd = Ovl->function_end();
1475         Func != FuncEnd; ++Func) {
1476      FunctionDecl *FDecl = cast<FunctionDecl>(*Func);
1477
1478      // Add the namespace in which this function was defined. Note
1479      // that, if this is a member function, we do *not* consider the
1480      // enclosing namespace of its class.
1481      DeclContext *Ctx = FDecl->getDeclContext();
1482      if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1483        AssociatedNamespaces.insert(EnclosingNamespace);
1484
1485      // Add the classes and namespaces associated with the parameter
1486      // types and return type of this function.
1487      addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1488                                        AssociatedNamespaces, AssociatedClasses);
1489    }
1490  }
1491}
1492
1493/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1494/// an acceptable non-member overloaded operator for a call whose
1495/// arguments have types T1 (and, if non-empty, T2). This routine
1496/// implements the check in C++ [over.match.oper]p3b2 concerning
1497/// enumeration types.
1498static bool
1499IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1500                                       QualType T1, QualType T2,
1501                                       ASTContext &Context) {
1502  if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1503    return true;
1504
1505  if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1506    return true;
1507
1508  const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1509  if (Proto->getNumArgs() < 1)
1510    return false;
1511
1512  if (T1->isEnumeralType()) {
1513    QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1514    if (Context.getCanonicalType(T1).getUnqualifiedType()
1515          == Context.getCanonicalType(ArgType).getUnqualifiedType())
1516      return true;
1517  }
1518
1519  if (Proto->getNumArgs() < 2)
1520    return false;
1521
1522  if (!T2.isNull() && T2->isEnumeralType()) {
1523    QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1524    if (Context.getCanonicalType(T2).getUnqualifiedType()
1525          == Context.getCanonicalType(ArgType).getUnqualifiedType())
1526      return true;
1527  }
1528
1529  return false;
1530}
1531
1532/// \brief Find the protocol with the given name, if any.
1533ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
1534  Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
1535  return cast_or_null<ObjCProtocolDecl>(D);
1536}
1537
1538/// \brief Find the Objective-C implementation with the given name, if
1539/// any.
1540ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1541  Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1542  return cast_or_null<ObjCImplementationDecl>(D);
1543}
1544
1545/// \brief Find the Objective-C category implementation with the given
1546/// name, if any.
1547ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1548  Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1549  return cast_or_null<ObjCCategoryImplDecl>(D);
1550}
1551
1552void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1553                                        QualType T1, QualType T2,
1554                                        FunctionSet &Functions) {
1555  // C++ [over.match.oper]p3:
1556  //     -- The set of non-member candidates is the result of the
1557  //        unqualified lookup of operator@ in the context of the
1558  //        expression according to the usual rules for name lookup in
1559  //        unqualified function calls (3.4.2) except that all member
1560  //        functions are ignored. However, if no operand has a class
1561  //        type, only those non-member functions in the lookup set
1562  //        that have a first parameter of type T1 or “reference to
1563  //        (possibly cv-qualified) T1”, when T1 is an enumeration
1564  //        type, or (if there is a right operand) a second parameter
1565  //        of type T2 or “reference to (possibly cv-qualified) T2”,
1566  //        when T2 is an enumeration type, are candidate functions.
1567  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1568  LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1569
1570  assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1571
1572  if (!Operators)
1573    return;
1574
1575  for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1576       Op != OpEnd; ++Op) {
1577    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1578      if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1579        Functions.insert(FD); // FIXME: canonical FD
1580  }
1581}
1582
1583void Sema::ArgumentDependentLookup(DeclarationName Name,
1584                                   Expr **Args, unsigned NumArgs,
1585                                   FunctionSet &Functions) {
1586  // Find all of the associated namespaces and classes based on the
1587  // arguments we have.
1588  AssociatedNamespaceSet AssociatedNamespaces;
1589  AssociatedClassSet AssociatedClasses;
1590  FindAssociatedClassesAndNamespaces(Args, NumArgs,
1591                                     AssociatedNamespaces, AssociatedClasses);
1592
1593  // C++ [basic.lookup.argdep]p3:
1594  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
1595  //   and let Y be the lookup set produced by argument dependent
1596  //   lookup (defined as follows). If X contains [...] then Y is
1597  //   empty. Otherwise Y is the set of declarations found in the
1598  //   namespaces associated with the argument types as described
1599  //   below. The set of declarations found by the lookup of the name
1600  //   is the union of X and Y.
1601  //
1602  // Here, we compute Y and add its members to the overloaded
1603  // candidate set.
1604  for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1605                                     NSEnd = AssociatedNamespaces.end();
1606       NS != NSEnd; ++NS) {
1607    //   When considering an associated namespace, the lookup is the
1608    //   same as the lookup performed when the associated namespace is
1609    //   used as a qualifier (3.4.3.2) except that:
1610    //
1611    //     -- Any using-directives in the associated namespace are
1612    //        ignored.
1613    //
1614    //     -- FIXME: Any namespace-scope friend functions declared in
1615    //        associated classes are visible within their respective
1616    //        namespaces even if they are not visible during an ordinary
1617    //        lookup (11.4).
1618    DeclContext::lookup_iterator I, E;
1619    for (llvm::tie(I, E) = (*NS)->lookup(Context, Name); I != E; ++I) {
1620      FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1621      if (!Func)
1622        break;
1623
1624      Functions.insert(Func);
1625    }
1626  }
1627}
1628