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