SemaLookup.cpp revision 09d19efaa147762f84aed55efa7930bb3616a4e5
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 "clang/Sema/Lookup.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclLookups.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ExternalSemaSource.h"
28#include "clang/Sema/Overload.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/TemplateDeduction.h"
34#include "clang/Sema/TypoCorrection.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/SetVector.h"
37#include "llvm/ADT/SmallPtrSet.h"
38#include "llvm/ADT/StringMap.h"
39#include "llvm/ADT/TinyPtrVector.h"
40#include "llvm/ADT/edit_distance.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <algorithm>
43#include <iterator>
44#include <limits>
45#include <list>
46#include <map>
47#include <set>
48#include <utility>
49#include <vector>
50
51using namespace clang;
52using namespace sema;
53
54namespace {
55  class UnqualUsingEntry {
56    const DeclContext *Nominated;
57    const DeclContext *CommonAncestor;
58
59  public:
60    UnqualUsingEntry(const DeclContext *Nominated,
61                     const DeclContext *CommonAncestor)
62      : Nominated(Nominated), CommonAncestor(CommonAncestor) {
63    }
64
65    const DeclContext *getCommonAncestor() const {
66      return CommonAncestor;
67    }
68
69    const DeclContext *getNominatedNamespace() const {
70      return Nominated;
71    }
72
73    // Sort by the pointer value of the common ancestor.
74    struct Comparator {
75      bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76        return L.getCommonAncestor() < R.getCommonAncestor();
77      }
78
79      bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80        return E.getCommonAncestor() < DC;
81      }
82
83      bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84        return DC < E.getCommonAncestor();
85      }
86    };
87  };
88
89  /// A collection of using directives, as used by C++ unqualified
90  /// lookup.
91  class UnqualUsingDirectiveSet {
92    typedef SmallVector<UnqualUsingEntry, 8> ListTy;
93
94    ListTy list;
95    llvm::SmallPtrSet<DeclContext*, 8> visited;
96
97  public:
98    UnqualUsingDirectiveSet() {}
99
100    void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
101      // C++ [namespace.udir]p1:
102      //   During unqualified name lookup, the names appear as if they
103      //   were declared in the nearest enclosing namespace which contains
104      //   both the using-directive and the nominated namespace.
105      DeclContext *InnermostFileDC
106        = static_cast<DeclContext*>(InnermostFileScope->getEntity());
107      assert(InnermostFileDC && InnermostFileDC->isFileContext());
108
109      for (; S; S = S->getParent()) {
110        // C++ [namespace.udir]p1:
111        //   A using-directive shall not appear in class scope, but may
112        //   appear in namespace scope or in block scope.
113        DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
114        if (Ctx && Ctx->isFileContext()) {
115          visit(Ctx, Ctx);
116        } else if (!Ctx || Ctx->isFunctionOrMethod()) {
117          Scope::udir_iterator I = S->using_directives_begin(),
118                             End = S->using_directives_end();
119          for (; I != End; ++I)
120            visit(*I, InnermostFileDC);
121        }
122      }
123    }
124
125    // Visits a context and collect all of its using directives
126    // recursively.  Treats all using directives as if they were
127    // declared in the context.
128    //
129    // A given context is only every visited once, so it is important
130    // that contexts be visited from the inside out in order to get
131    // the effective DCs right.
132    void visit(DeclContext *DC, DeclContext *EffectiveDC) {
133      if (!visited.insert(DC))
134        return;
135
136      addUsingDirectives(DC, EffectiveDC);
137    }
138
139    // Visits a using directive and collects all of its using
140    // directives recursively.  Treats all using directives as if they
141    // were declared in the effective DC.
142    void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
143      DeclContext *NS = UD->getNominatedNamespace();
144      if (!visited.insert(NS))
145        return;
146
147      addUsingDirective(UD, EffectiveDC);
148      addUsingDirectives(NS, EffectiveDC);
149    }
150
151    // Adds all the using directives in a context (and those nominated
152    // by its using directives, transitively) as if they appeared in
153    // the given effective context.
154    void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
155      SmallVector<DeclContext*,4> queue;
156      while (true) {
157        DeclContext::udir_iterator I, End;
158        for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
159          UsingDirectiveDecl *UD = *I;
160          DeclContext *NS = UD->getNominatedNamespace();
161          if (visited.insert(NS)) {
162            addUsingDirective(UD, EffectiveDC);
163            queue.push_back(NS);
164          }
165        }
166
167        if (queue.empty())
168          return;
169
170        DC = queue.back();
171        queue.pop_back();
172      }
173    }
174
175    // Add a using directive as if it had been declared in the given
176    // context.  This helps implement C++ [namespace.udir]p3:
177    //   The using-directive is transitive: if a scope contains a
178    //   using-directive that nominates a second namespace that itself
179    //   contains using-directives, the effect is as if the
180    //   using-directives from the second namespace also appeared in
181    //   the first.
182    void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
183      // Find the common ancestor between the effective context and
184      // the nominated namespace.
185      DeclContext *Common = UD->getNominatedNamespace();
186      while (!Common->Encloses(EffectiveDC))
187        Common = Common->getParent();
188      Common = Common->getPrimaryContext();
189
190      list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
191    }
192
193    void done() {
194      std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
195    }
196
197    typedef ListTy::const_iterator const_iterator;
198
199    const_iterator begin() const { return list.begin(); }
200    const_iterator end() const { return list.end(); }
201
202    std::pair<const_iterator,const_iterator>
203    getNamespacesFor(DeclContext *DC) const {
204      return std::equal_range(begin(), end(), DC->getPrimaryContext(),
205                              UnqualUsingEntry::Comparator());
206    }
207  };
208}
209
210// Retrieve the set of identifier namespaces that correspond to a
211// specific kind of name lookup.
212static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
213                               bool CPlusPlus,
214                               bool Redeclaration) {
215  unsigned IDNS = 0;
216  switch (NameKind) {
217  case Sema::LookupObjCImplicitSelfParam:
218  case Sema::LookupOrdinaryName:
219  case Sema::LookupRedeclarationWithLinkage:
220    IDNS = Decl::IDNS_Ordinary;
221    if (CPlusPlus) {
222      IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
223      if (Redeclaration)
224        IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
225    }
226    break;
227
228  case Sema::LookupOperatorName:
229    // Operator lookup is its own crazy thing;  it is not the same
230    // as (e.g.) looking up an operator name for redeclaration.
231    assert(!Redeclaration && "cannot do redeclaration operator lookup");
232    IDNS = Decl::IDNS_NonMemberOperator;
233    break;
234
235  case Sema::LookupTagName:
236    if (CPlusPlus) {
237      IDNS = Decl::IDNS_Type;
238
239      // When looking for a redeclaration of a tag name, we add:
240      // 1) TagFriend to find undeclared friend decls
241      // 2) Namespace because they can't "overload" with tag decls.
242      // 3) Tag because it includes class templates, which can't
243      //    "overload" with tag decls.
244      if (Redeclaration)
245        IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
246    } else {
247      IDNS = Decl::IDNS_Tag;
248    }
249    break;
250  case Sema::LookupLabel:
251    IDNS = Decl::IDNS_Label;
252    break;
253
254  case Sema::LookupMemberName:
255    IDNS = Decl::IDNS_Member;
256    if (CPlusPlus)
257      IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
258    break;
259
260  case Sema::LookupNestedNameSpecifierName:
261    IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
262    break;
263
264  case Sema::LookupNamespaceName:
265    IDNS = Decl::IDNS_Namespace;
266    break;
267
268  case Sema::LookupUsingDeclName:
269    IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
270         | Decl::IDNS_Member | Decl::IDNS_Using;
271    break;
272
273  case Sema::LookupObjCProtocolName:
274    IDNS = Decl::IDNS_ObjCProtocol;
275    break;
276
277  case Sema::LookupAnyName:
278    IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
279      | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
280      | Decl::IDNS_Type;
281    break;
282  }
283  return IDNS;
284}
285
286void LookupResult::configure() {
287  IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
288                 isForRedeclaration());
289
290  if (!isForRedeclaration()) {
291    // If we're looking for one of the allocation or deallocation
292    // operators, make sure that the implicitly-declared new and delete
293    // operators can be found.
294    switch (NameInfo.getName().getCXXOverloadedOperator()) {
295    case OO_New:
296    case OO_Delete:
297    case OO_Array_New:
298    case OO_Array_Delete:
299      SemaRef.DeclareGlobalNewDelete();
300      break;
301
302    default:
303      break;
304    }
305
306    // Compiler builtins are always visible, regardless of where they end
307    // up being declared.
308    if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
309      if (unsigned BuiltinID = Id->getBuiltinID()) {
310        if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
311          AllowHidden = true;
312      }
313    }
314  }
315}
316
317void LookupResult::sanityImpl() const {
318  // Note that this function is never called by NDEBUG builds. See
319  // LookupResult::sanity().
320  assert(ResultKind != NotFound || Decls.size() == 0);
321  assert(ResultKind != Found || Decls.size() == 1);
322  assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
323         (Decls.size() == 1 &&
324          isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
325  assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
326  assert(ResultKind != Ambiguous || Decls.size() > 1 ||
327         (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
328                                Ambiguity == AmbiguousBaseSubobjectTypes)));
329  assert((Paths != NULL) == (ResultKind == Ambiguous &&
330                             (Ambiguity == AmbiguousBaseSubobjectTypes ||
331                              Ambiguity == AmbiguousBaseSubobjects)));
332}
333
334// Necessary because CXXBasePaths is not complete in Sema.h
335void LookupResult::deletePaths(CXXBasePaths *Paths) {
336  delete Paths;
337}
338
339static NamedDecl *getVisibleDecl(NamedDecl *D);
340
341NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
342  return getVisibleDecl(D);
343}
344
345/// Resolves the result kind of this lookup.
346void LookupResult::resolveKind() {
347  unsigned N = Decls.size();
348
349  // Fast case: no possible ambiguity.
350  if (N == 0) {
351    assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
352    return;
353  }
354
355  // If there's a single decl, we need to examine it to decide what
356  // kind of lookup this is.
357  if (N == 1) {
358    NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
359    if (isa<FunctionTemplateDecl>(D))
360      ResultKind = FoundOverloaded;
361    else if (isa<UnresolvedUsingValueDecl>(D))
362      ResultKind = FoundUnresolvedValue;
363    return;
364  }
365
366  // Don't do any extra resolution if we've already resolved as ambiguous.
367  if (ResultKind == Ambiguous) return;
368
369  llvm::SmallPtrSet<NamedDecl*, 16> Unique;
370  llvm::SmallPtrSet<QualType, 16> UniqueTypes;
371
372  bool Ambiguous = false;
373  bool HasTag = false, HasFunction = false, HasNonFunction = false;
374  bool HasFunctionTemplate = false, HasUnresolved = false;
375
376  unsigned UniqueTagIndex = 0;
377
378  unsigned I = 0;
379  while (I < N) {
380    NamedDecl *D = Decls[I]->getUnderlyingDecl();
381    D = cast<NamedDecl>(D->getCanonicalDecl());
382
383    // Ignore an invalid declaration unless it's the only one left.
384    if (D->isInvalidDecl() && I < N-1) {
385      Decls[I] = Decls[--N];
386      continue;
387    }
388
389    // Redeclarations of types via typedef can occur both within a scope
390    // and, through using declarations and directives, across scopes. There is
391    // no ambiguity if they all refer to the same type, so unique based on the
392    // canonical type.
393    if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
394      if (!TD->getDeclContext()->isRecord()) {
395        QualType T = SemaRef.Context.getTypeDeclType(TD);
396        if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
397          // The type is not unique; pull something off the back and continue
398          // at this index.
399          Decls[I] = Decls[--N];
400          continue;
401        }
402      }
403    }
404
405    if (!Unique.insert(D)) {
406      // If it's not unique, pull something off the back (and
407      // continue at this index).
408      Decls[I] = Decls[--N];
409      continue;
410    }
411
412    // Otherwise, do some decl type analysis and then continue.
413
414    if (isa<UnresolvedUsingValueDecl>(D)) {
415      HasUnresolved = true;
416    } else if (isa<TagDecl>(D)) {
417      if (HasTag)
418        Ambiguous = true;
419      UniqueTagIndex = I;
420      HasTag = true;
421    } else if (isa<FunctionTemplateDecl>(D)) {
422      HasFunction = true;
423      HasFunctionTemplate = true;
424    } else if (isa<FunctionDecl>(D)) {
425      HasFunction = true;
426    } else {
427      if (HasNonFunction)
428        Ambiguous = true;
429      HasNonFunction = true;
430    }
431    I++;
432  }
433
434  // C++ [basic.scope.hiding]p2:
435  //   A class name or enumeration name can be hidden by the name of
436  //   an object, function, or enumerator declared in the same
437  //   scope. If a class or enumeration name and an object, function,
438  //   or enumerator are declared in the same scope (in any order)
439  //   with the same name, the class or enumeration name is hidden
440  //   wherever the object, function, or enumerator name is visible.
441  // But it's still an error if there are distinct tag types found,
442  // even if they're not visible. (ref?)
443  if (HideTags && HasTag && !Ambiguous &&
444      (HasFunction || HasNonFunction || HasUnresolved)) {
445    if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
446         Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
447      Decls[UniqueTagIndex] = Decls[--N];
448    else
449      Ambiguous = true;
450  }
451
452  Decls.set_size(N);
453
454  if (HasNonFunction && (HasFunction || HasUnresolved))
455    Ambiguous = true;
456
457  if (Ambiguous)
458    setAmbiguous(LookupResult::AmbiguousReference);
459  else if (HasUnresolved)
460    ResultKind = LookupResult::FoundUnresolvedValue;
461  else if (N > 1 || HasFunctionTemplate)
462    ResultKind = LookupResult::FoundOverloaded;
463  else
464    ResultKind = LookupResult::Found;
465}
466
467void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
468  CXXBasePaths::const_paths_iterator I, E;
469  for (I = P.begin(), E = P.end(); I != E; ++I)
470    for (DeclContext::lookup_iterator DI = I->Decls.begin(),
471         DE = I->Decls.end(); DI != DE; ++DI)
472      addDecl(*DI);
473}
474
475void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
476  Paths = new CXXBasePaths;
477  Paths->swap(P);
478  addDeclsFromBasePaths(*Paths);
479  resolveKind();
480  setAmbiguous(AmbiguousBaseSubobjects);
481}
482
483void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
484  Paths = new CXXBasePaths;
485  Paths->swap(P);
486  addDeclsFromBasePaths(*Paths);
487  resolveKind();
488  setAmbiguous(AmbiguousBaseSubobjectTypes);
489}
490
491void LookupResult::print(raw_ostream &Out) {
492  Out << Decls.size() << " result(s)";
493  if (isAmbiguous()) Out << ", ambiguous";
494  if (Paths) Out << ", base paths present";
495
496  for (iterator I = begin(), E = end(); I != E; ++I) {
497    Out << "\n";
498    (*I)->print(Out, 2);
499  }
500}
501
502/// \brief Lookup a builtin function, when name lookup would otherwise
503/// fail.
504static bool LookupBuiltin(Sema &S, LookupResult &R) {
505  Sema::LookupNameKind NameKind = R.getLookupKind();
506
507  // If we didn't find a use of this identifier, and if the identifier
508  // corresponds to a compiler builtin, create the decl object for the builtin
509  // now, injecting it into translation unit scope, and return it.
510  if (NameKind == Sema::LookupOrdinaryName ||
511      NameKind == Sema::LookupRedeclarationWithLinkage) {
512    IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
513    if (II) {
514      if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
515          II == S.getFloat128Identifier()) {
516        // libstdc++4.7's type_traits expects type __float128 to exist, so
517        // insert a dummy type to make that header build in gnu++11 mode.
518        R.addDecl(S.getASTContext().getFloat128StubType());
519        return true;
520      }
521
522      // If this is a builtin on this (or all) targets, create the decl.
523      if (unsigned BuiltinID = II->getBuiltinID()) {
524        // In C++, we don't have any predefined library functions like
525        // 'malloc'. Instead, we'll just error.
526        if (S.getLangOpts().CPlusPlus &&
527            S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
528          return false;
529
530        if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
531                                                 BuiltinID, S.TUScope,
532                                                 R.isForRedeclaration(),
533                                                 R.getNameLoc())) {
534          R.addDecl(D);
535          return true;
536        }
537
538        if (R.isForRedeclaration()) {
539          // If we're redeclaring this function anyway, forget that
540          // this was a builtin at all.
541          S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
542        }
543
544        return false;
545      }
546    }
547  }
548
549  return false;
550}
551
552/// \brief Determine whether we can declare a special member function within
553/// the class at this point.
554static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
555  // We need to have a definition for the class.
556  if (!Class->getDefinition() || Class->isDependentContext())
557    return false;
558
559  // We can't be in the middle of defining the class.
560  return !Class->isBeingDefined();
561}
562
563void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
564  if (!CanDeclareSpecialMemberFunction(Class))
565    return;
566
567  // If the default constructor has not yet been declared, do so now.
568  if (Class->needsImplicitDefaultConstructor())
569    DeclareImplicitDefaultConstructor(Class);
570
571  // If the copy constructor has not yet been declared, do so now.
572  if (Class->needsImplicitCopyConstructor())
573    DeclareImplicitCopyConstructor(Class);
574
575  // If the copy assignment operator has not yet been declared, do so now.
576  if (Class->needsImplicitCopyAssignment())
577    DeclareImplicitCopyAssignment(Class);
578
579  if (getLangOpts().CPlusPlus11) {
580    // If the move constructor has not yet been declared, do so now.
581    if (Class->needsImplicitMoveConstructor())
582      DeclareImplicitMoveConstructor(Class); // might not actually do it
583
584    // If the move assignment operator has not yet been declared, do so now.
585    if (Class->needsImplicitMoveAssignment())
586      DeclareImplicitMoveAssignment(Class); // might not actually do it
587  }
588
589  // If the destructor has not yet been declared, do so now.
590  if (Class->needsImplicitDestructor())
591    DeclareImplicitDestructor(Class);
592}
593
594/// \brief Determine whether this is the name of an implicitly-declared
595/// special member function.
596static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
597  switch (Name.getNameKind()) {
598  case DeclarationName::CXXConstructorName:
599  case DeclarationName::CXXDestructorName:
600    return true;
601
602  case DeclarationName::CXXOperatorName:
603    return Name.getCXXOverloadedOperator() == OO_Equal;
604
605  default:
606    break;
607  }
608
609  return false;
610}
611
612/// \brief If there are any implicit member functions with the given name
613/// that need to be declared in the given declaration context, do so.
614static void DeclareImplicitMemberFunctionsWithName(Sema &S,
615                                                   DeclarationName Name,
616                                                   const DeclContext *DC) {
617  if (!DC)
618    return;
619
620  switch (Name.getNameKind()) {
621  case DeclarationName::CXXConstructorName:
622    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
623      if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
624        CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
625        if (Record->needsImplicitDefaultConstructor())
626          S.DeclareImplicitDefaultConstructor(Class);
627        if (Record->needsImplicitCopyConstructor())
628          S.DeclareImplicitCopyConstructor(Class);
629        if (S.getLangOpts().CPlusPlus11 &&
630            Record->needsImplicitMoveConstructor())
631          S.DeclareImplicitMoveConstructor(Class);
632      }
633    break;
634
635  case DeclarationName::CXXDestructorName:
636    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
637      if (Record->getDefinition() && Record->needsImplicitDestructor() &&
638          CanDeclareSpecialMemberFunction(Record))
639        S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
640    break;
641
642  case DeclarationName::CXXOperatorName:
643    if (Name.getCXXOverloadedOperator() != OO_Equal)
644      break;
645
646    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
647      if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
648        CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
649        if (Record->needsImplicitCopyAssignment())
650          S.DeclareImplicitCopyAssignment(Class);
651        if (S.getLangOpts().CPlusPlus11 &&
652            Record->needsImplicitMoveAssignment())
653          S.DeclareImplicitMoveAssignment(Class);
654      }
655    }
656    break;
657
658  default:
659    break;
660  }
661}
662
663// Adds all qualifying matches for a name within a decl context to the
664// given lookup result.  Returns true if any matches were found.
665static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
666  bool Found = false;
667
668  // Lazily declare C++ special member functions.
669  if (S.getLangOpts().CPlusPlus)
670    DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
671
672  // Perform lookup into this declaration context.
673  DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
674  for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
675       ++I) {
676    NamedDecl *D = *I;
677    if ((D = R.getAcceptableDecl(D))) {
678      R.addDecl(D);
679      Found = true;
680    }
681  }
682
683  if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
684    return true;
685
686  if (R.getLookupName().getNameKind()
687        != DeclarationName::CXXConversionFunctionName ||
688      R.getLookupName().getCXXNameType()->isDependentType() ||
689      !isa<CXXRecordDecl>(DC))
690    return Found;
691
692  // C++ [temp.mem]p6:
693  //   A specialization of a conversion function template is not found by
694  //   name lookup. Instead, any conversion function templates visible in the
695  //   context of the use are considered. [...]
696  const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
697  if (!Record->isCompleteDefinition())
698    return Found;
699
700  for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
701         UEnd = Record->conversion_end(); U != UEnd; ++U) {
702    FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
703    if (!ConvTemplate)
704      continue;
705
706    // When we're performing lookup for the purposes of redeclaration, just
707    // add the conversion function template. When we deduce template
708    // arguments for specializations, we'll end up unifying the return
709    // type of the new declaration with the type of the function template.
710    if (R.isForRedeclaration()) {
711      R.addDecl(ConvTemplate);
712      Found = true;
713      continue;
714    }
715
716    // C++ [temp.mem]p6:
717    //   [...] For each such operator, if argument deduction succeeds
718    //   (14.9.2.3), the resulting specialization is used as if found by
719    //   name lookup.
720    //
721    // When referencing a conversion function for any purpose other than
722    // a redeclaration (such that we'll be building an expression with the
723    // result), perform template argument deduction and place the
724    // specialization into the result set. We do this to avoid forcing all
725    // callers to perform special deduction for conversion functions.
726    TemplateDeductionInfo Info(R.getNameLoc());
727    FunctionDecl *Specialization = 0;
728
729    const FunctionProtoType *ConvProto
730      = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
731    assert(ConvProto && "Nonsensical conversion function template type");
732
733    // Compute the type of the function that we would expect the conversion
734    // function to have, if it were to match the name given.
735    // FIXME: Calling convention!
736    FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
737    EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
738    EPI.ExceptionSpecType = EST_None;
739    EPI.NumExceptions = 0;
740    QualType ExpectedType
741      = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
742                                            None, EPI);
743
744    // Perform template argument deduction against the type that we would
745    // expect the function to have.
746    if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
747                                            Specialization, Info)
748          == Sema::TDK_Success) {
749      R.addDecl(Specialization);
750      Found = true;
751    }
752  }
753
754  return Found;
755}
756
757// Performs C++ unqualified lookup into the given file context.
758static bool
759CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
760                   DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
761
762  assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
763
764  // Perform direct name lookup into the LookupCtx.
765  bool Found = LookupDirect(S, R, NS);
766
767  // Perform direct name lookup into the namespaces nominated by the
768  // using directives whose common ancestor is this namespace.
769  UnqualUsingDirectiveSet::const_iterator UI, UEnd;
770  llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
771
772  for (; UI != UEnd; ++UI)
773    if (LookupDirect(S, R, UI->getNominatedNamespace()))
774      Found = true;
775
776  R.resolveKind();
777
778  return Found;
779}
780
781static bool isNamespaceOrTranslationUnitScope(Scope *S) {
782  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
783    return Ctx->isFileContext();
784  return false;
785}
786
787// Find the next outer declaration context from this scope. This
788// routine actually returns the semantic outer context, which may
789// differ from the lexical context (encoded directly in the Scope
790// stack) when we are parsing a member of a class template. In this
791// case, the second element of the pair will be true, to indicate that
792// name lookup should continue searching in this semantic context when
793// it leaves the current template parameter scope.
794static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
795  DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
796  DeclContext *Lexical = 0;
797  for (Scope *OuterS = S->getParent(); OuterS;
798       OuterS = OuterS->getParent()) {
799    if (OuterS->getEntity()) {
800      Lexical = static_cast<DeclContext *>(OuterS->getEntity());
801      break;
802    }
803  }
804
805  // C++ [temp.local]p8:
806  //   In the definition of a member of a class template that appears
807  //   outside of the namespace containing the class template
808  //   definition, the name of a template-parameter hides the name of
809  //   a member of this namespace.
810  //
811  // Example:
812  //
813  //   namespace N {
814  //     class C { };
815  //
816  //     template<class T> class B {
817  //       void f(T);
818  //     };
819  //   }
820  //
821  //   template<class C> void N::B<C>::f(C) {
822  //     C b;  // C is the template parameter, not N::C
823  //   }
824  //
825  // In this example, the lexical context we return is the
826  // TranslationUnit, while the semantic context is the namespace N.
827  if (!Lexical || !DC || !S->getParent() ||
828      !S->getParent()->isTemplateParamScope())
829    return std::make_pair(Lexical, false);
830
831  // Find the outermost template parameter scope.
832  // For the example, this is the scope for the template parameters of
833  // template<class C>.
834  Scope *OutermostTemplateScope = S->getParent();
835  while (OutermostTemplateScope->getParent() &&
836         OutermostTemplateScope->getParent()->isTemplateParamScope())
837    OutermostTemplateScope = OutermostTemplateScope->getParent();
838
839  // Find the namespace context in which the original scope occurs. In
840  // the example, this is namespace N.
841  DeclContext *Semantic = DC;
842  while (!Semantic->isFileContext())
843    Semantic = Semantic->getParent();
844
845  // Find the declaration context just outside of the template
846  // parameter scope. This is the context in which the template is
847  // being lexically declaration (a namespace context). In the
848  // example, this is the global scope.
849  if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
850      Lexical->Encloses(Semantic))
851    return std::make_pair(Semantic, true);
852
853  return std::make_pair(Lexical, false);
854}
855
856bool Sema::CppLookupName(LookupResult &R, Scope *S) {
857  assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
858
859  DeclarationName Name = R.getLookupName();
860
861  // If this is the name of an implicitly-declared special member function,
862  // go through the scope stack to implicitly declare
863  if (isImplicitlyDeclaredMemberFunctionName(Name)) {
864    for (Scope *PreS = S; PreS; PreS = PreS->getParent())
865      if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
866        DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
867  }
868
869  // Implicitly declare member functions with the name we're looking for, if in
870  // fact we are in a scope where it matters.
871
872  Scope *Initial = S;
873  IdentifierResolver::iterator
874    I = IdResolver.begin(Name),
875    IEnd = IdResolver.end();
876
877  // First we lookup local scope.
878  // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
879  // ...During unqualified name lookup (3.4.1), the names appear as if
880  // they were declared in the nearest enclosing namespace which contains
881  // both the using-directive and the nominated namespace.
882  // [Note: in this context, "contains" means "contains directly or
883  // indirectly".
884  //
885  // For example:
886  // namespace A { int i; }
887  // void foo() {
888  //   int i;
889  //   {
890  //     using namespace A;
891  //     ++i; // finds local 'i', A::i appears at global scope
892  //   }
893  // }
894  //
895  UnqualUsingDirectiveSet UDirs;
896  bool VisitedUsingDirectives = false;
897  DeclContext *OutsideOfTemplateParamDC = 0;
898  for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
899    DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
900
901    // Check whether the IdResolver has anything in this scope.
902    bool Found = false;
903    for (; I != IEnd && S->isDeclScope(*I); ++I) {
904      if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
905        Found = true;
906        R.addDecl(ND);
907      }
908    }
909    if (Found) {
910      R.resolveKind();
911      if (S->isClassScope())
912        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
913          R.setNamingClass(Record);
914      return true;
915    }
916
917    if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
918        S->getParent() && !S->getParent()->isTemplateParamScope()) {
919      // We've just searched the last template parameter scope and
920      // found nothing, so look into the contexts between the
921      // lexical and semantic declaration contexts returned by
922      // findOuterContext(). This implements the name lookup behavior
923      // of C++ [temp.local]p8.
924      Ctx = OutsideOfTemplateParamDC;
925      OutsideOfTemplateParamDC = 0;
926    }
927
928    if (Ctx) {
929      DeclContext *OuterCtx;
930      bool SearchAfterTemplateScope;
931      llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
932      if (SearchAfterTemplateScope)
933        OutsideOfTemplateParamDC = OuterCtx;
934
935      for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
936        // We do not directly look into transparent contexts, since
937        // those entities will be found in the nearest enclosing
938        // non-transparent context.
939        if (Ctx->isTransparentContext())
940          continue;
941
942        // We do not look directly into function or method contexts,
943        // since all of the local variables and parameters of the
944        // function/method are present within the Scope.
945        if (Ctx->isFunctionOrMethod()) {
946          // If we have an Objective-C instance method, look for ivars
947          // in the corresponding interface.
948          if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
949            if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
950              if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
951                ObjCInterfaceDecl *ClassDeclared;
952                if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
953                                                 Name.getAsIdentifierInfo(),
954                                                             ClassDeclared)) {
955                  if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
956                    R.addDecl(ND);
957                    R.resolveKind();
958                    return true;
959                  }
960                }
961              }
962          }
963
964          continue;
965        }
966
967        // If this is a file context, we need to perform unqualified name
968        // lookup considering using directives.
969        if (Ctx->isFileContext()) {
970          // If we haven't handled using directives yet, do so now.
971          if (!VisitedUsingDirectives) {
972            // Add using directives from this context up to the top level.
973            for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
974              if (UCtx->isTransparentContext())
975                continue;
976
977              UDirs.visit(UCtx, UCtx);
978            }
979
980            // Find the innermost file scope, so we can add using directives
981            // from local scopes.
982            Scope *InnermostFileScope = S;
983            while (InnermostFileScope &&
984                   !isNamespaceOrTranslationUnitScope(InnermostFileScope))
985              InnermostFileScope = InnermostFileScope->getParent();
986            UDirs.visitScopeChain(Initial, InnermostFileScope);
987
988            UDirs.done();
989
990            VisitedUsingDirectives = true;
991          }
992
993          if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
994            R.resolveKind();
995            return true;
996          }
997
998          continue;
999        }
1000
1001        // Perform qualified name lookup into this context.
1002        // FIXME: In some cases, we know that every name that could be found by
1003        // this qualified name lookup will also be on the identifier chain. For
1004        // example, inside a class without any base classes, we never need to
1005        // perform qualified lookup because all of the members are on top of the
1006        // identifier chain.
1007        if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1008          return true;
1009      }
1010    }
1011  }
1012
1013  // Stop if we ran out of scopes.
1014  // FIXME:  This really, really shouldn't be happening.
1015  if (!S) return false;
1016
1017  // If we are looking for members, no need to look into global/namespace scope.
1018  if (R.getLookupKind() == LookupMemberName)
1019    return false;
1020
1021  // Collect UsingDirectiveDecls in all scopes, and recursively all
1022  // nominated namespaces by those using-directives.
1023  //
1024  // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1025  // don't build it for each lookup!
1026  if (!VisitedUsingDirectives) {
1027    UDirs.visitScopeChain(Initial, S);
1028    UDirs.done();
1029  }
1030
1031  // Lookup namespace scope, and global scope.
1032  // Unqualified name lookup in C++ requires looking into scopes
1033  // that aren't strictly lexical, and therefore we walk through the
1034  // context as well as walking through the scopes.
1035  for (; S; S = S->getParent()) {
1036    // Check whether the IdResolver has anything in this scope.
1037    bool Found = false;
1038    for (; I != IEnd && S->isDeclScope(*I); ++I) {
1039      if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1040        // We found something.  Look for anything else in our scope
1041        // with this same name and in an acceptable identifier
1042        // namespace, so that we can construct an overload set if we
1043        // need to.
1044        Found = true;
1045        R.addDecl(ND);
1046      }
1047    }
1048
1049    if (Found && S->isTemplateParamScope()) {
1050      R.resolveKind();
1051      return true;
1052    }
1053
1054    DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1055    if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1056        S->getParent() && !S->getParent()->isTemplateParamScope()) {
1057      // We've just searched the last template parameter scope and
1058      // found nothing, so look into the contexts between the
1059      // lexical and semantic declaration contexts returned by
1060      // findOuterContext(). This implements the name lookup behavior
1061      // of C++ [temp.local]p8.
1062      Ctx = OutsideOfTemplateParamDC;
1063      OutsideOfTemplateParamDC = 0;
1064    }
1065
1066    if (Ctx) {
1067      DeclContext *OuterCtx;
1068      bool SearchAfterTemplateScope;
1069      llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1070      if (SearchAfterTemplateScope)
1071        OutsideOfTemplateParamDC = OuterCtx;
1072
1073      for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1074        // We do not directly look into transparent contexts, since
1075        // those entities will be found in the nearest enclosing
1076        // non-transparent context.
1077        if (Ctx->isTransparentContext())
1078          continue;
1079
1080        // If we have a context, and it's not a context stashed in the
1081        // template parameter scope for an out-of-line definition, also
1082        // look into that context.
1083        if (!(Found && S && S->isTemplateParamScope())) {
1084          assert(Ctx->isFileContext() &&
1085              "We should have been looking only at file context here already.");
1086
1087          // Look into context considering using-directives.
1088          if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1089            Found = true;
1090        }
1091
1092        if (Found) {
1093          R.resolveKind();
1094          return true;
1095        }
1096
1097        if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1098          return false;
1099      }
1100    }
1101
1102    if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1103      return false;
1104  }
1105
1106  return !R.empty();
1107}
1108
1109/// \brief Retrieve the visible declaration corresponding to D, if any.
1110///
1111/// This routine determines whether the declaration D is visible in the current
1112/// module, with the current imports. If not, it checks whether any
1113/// redeclaration of D is visible, and if so, returns that declaration.
1114///
1115/// \returns D, or a visible previous declaration of D, whichever is more recent
1116/// and visible. If no declaration of D is visible, returns null.
1117static NamedDecl *getVisibleDecl(NamedDecl *D) {
1118  if (LookupResult::isVisible(D))
1119    return D;
1120
1121  for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1122       RD != RDEnd; ++RD) {
1123    if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1124      if (LookupResult::isVisible(ND))
1125        return ND;
1126    }
1127  }
1128
1129  return 0;
1130}
1131
1132/// @brief Perform unqualified name lookup starting from a given
1133/// scope.
1134///
1135/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1136/// used to find names within the current scope. For example, 'x' in
1137/// @code
1138/// int x;
1139/// int f() {
1140///   return x; // unqualified name look finds 'x' in the global scope
1141/// }
1142/// @endcode
1143///
1144/// Different lookup criteria can find different names. For example, a
1145/// particular scope can have both a struct and a function of the same
1146/// name, and each can be found by certain lookup criteria. For more
1147/// information about lookup criteria, see the documentation for the
1148/// class LookupCriteria.
1149///
1150/// @param S        The scope from which unqualified name lookup will
1151/// begin. If the lookup criteria permits, name lookup may also search
1152/// in the parent scopes.
1153///
1154/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1155/// look up and the lookup kind), and is updated with the results of lookup
1156/// including zero or more declarations and possibly additional information
1157/// used to diagnose ambiguities.
1158///
1159/// @returns \c true if lookup succeeded and false otherwise.
1160bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1161  DeclarationName Name = R.getLookupName();
1162  if (!Name) return false;
1163
1164  LookupNameKind NameKind = R.getLookupKind();
1165
1166  if (!getLangOpts().CPlusPlus) {
1167    // Unqualified name lookup in C/Objective-C is purely lexical, so
1168    // search in the declarations attached to the name.
1169    if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1170      // Find the nearest non-transparent declaration scope.
1171      while (!(S->getFlags() & Scope::DeclScope) ||
1172             (S->getEntity() &&
1173              static_cast<DeclContext *>(S->getEntity())
1174                ->isTransparentContext()))
1175        S = S->getParent();
1176    }
1177
1178    unsigned IDNS = R.getIdentifierNamespace();
1179
1180    // Scan up the scope chain looking for a decl that matches this
1181    // identifier that is in the appropriate namespace.  This search
1182    // should not take long, as shadowing of names is uncommon, and
1183    // deep shadowing is extremely uncommon.
1184    bool LeftStartingScope = false;
1185
1186    for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1187                                   IEnd = IdResolver.end();
1188         I != IEnd; ++I)
1189      if ((*I)->isInIdentifierNamespace(IDNS)) {
1190        if (NameKind == LookupRedeclarationWithLinkage) {
1191          // Determine whether this (or a previous) declaration is
1192          // out-of-scope.
1193          if (!LeftStartingScope && !S->isDeclScope(*I))
1194            LeftStartingScope = true;
1195
1196          // If we found something outside of our starting scope that
1197          // does not have linkage, skip it.
1198          if (LeftStartingScope && !((*I)->hasLinkage()))
1199            continue;
1200        }
1201        else if (NameKind == LookupObjCImplicitSelfParam &&
1202                 !isa<ImplicitParamDecl>(*I))
1203          continue;
1204
1205        // If this declaration is module-private and it came from an AST
1206        // file, we can't see it.
1207        NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
1208        if (!D)
1209          continue;
1210
1211        R.addDecl(D);
1212
1213        // Check whether there are any other declarations with the same name
1214        // and in the same scope.
1215        if (I != IEnd) {
1216          // Find the scope in which this declaration was declared (if it
1217          // actually exists in a Scope).
1218          while (S && !S->isDeclScope(D))
1219            S = S->getParent();
1220
1221          // If the scope containing the declaration is the translation unit,
1222          // then we'll need to perform our checks based on the matching
1223          // DeclContexts rather than matching scopes.
1224          if (S && isNamespaceOrTranslationUnitScope(S))
1225            S = 0;
1226
1227          // Compute the DeclContext, if we need it.
1228          DeclContext *DC = 0;
1229          if (!S)
1230            DC = (*I)->getDeclContext()->getRedeclContext();
1231
1232          IdentifierResolver::iterator LastI = I;
1233          for (++LastI; LastI != IEnd; ++LastI) {
1234            if (S) {
1235              // Match based on scope.
1236              if (!S->isDeclScope(*LastI))
1237                break;
1238            } else {
1239              // Match based on DeclContext.
1240              DeclContext *LastDC
1241                = (*LastI)->getDeclContext()->getRedeclContext();
1242              if (!LastDC->Equals(DC))
1243                break;
1244            }
1245
1246            // If the declaration isn't in the right namespace, skip it.
1247            if (!(*LastI)->isInIdentifierNamespace(IDNS))
1248              continue;
1249
1250            D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
1251            if (D)
1252              R.addDecl(D);
1253          }
1254
1255          R.resolveKind();
1256        }
1257        return true;
1258      }
1259  } else {
1260    // Perform C++ unqualified name lookup.
1261    if (CppLookupName(R, S))
1262      return true;
1263  }
1264
1265  // If we didn't find a use of this identifier, and if the identifier
1266  // corresponds to a compiler builtin, create the decl object for the builtin
1267  // now, injecting it into translation unit scope, and return it.
1268  if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1269    return true;
1270
1271  // If we didn't find a use of this identifier, the ExternalSource
1272  // may be able to handle the situation.
1273  // Note: some lookup failures are expected!
1274  // See e.g. R.isForRedeclaration().
1275  return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1276}
1277
1278/// @brief Perform qualified name lookup in the namespaces nominated by
1279/// using directives by the given context.
1280///
1281/// C++98 [namespace.qual]p2:
1282///   Given X::m (where X is a user-declared namespace), or given \::m
1283///   (where X is the global namespace), let S be the set of all
1284///   declarations of m in X and in the transitive closure of all
1285///   namespaces nominated by using-directives in X and its used
1286///   namespaces, except that using-directives are ignored in any
1287///   namespace, including X, directly containing one or more
1288///   declarations of m. No namespace is searched more than once in
1289///   the lookup of a name. If S is the empty set, the program is
1290///   ill-formed. Otherwise, if S has exactly one member, or if the
1291///   context of the reference is a using-declaration
1292///   (namespace.udecl), S is the required set of declarations of
1293///   m. Otherwise if the use of m is not one that allows a unique
1294///   declaration to be chosen from S, the program is ill-formed.
1295///
1296/// C++98 [namespace.qual]p5:
1297///   During the lookup of a qualified namespace member name, if the
1298///   lookup finds more than one declaration of the member, and if one
1299///   declaration introduces a class name or enumeration name and the
1300///   other declarations either introduce the same object, the same
1301///   enumerator or a set of functions, the non-type name hides the
1302///   class or enumeration name if and only if the declarations are
1303///   from the same namespace; otherwise (the declarations are from
1304///   different namespaces), the program is ill-formed.
1305static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1306                                                 DeclContext *StartDC) {
1307  assert(StartDC->isFileContext() && "start context is not a file context");
1308
1309  DeclContext::udir_iterator I = StartDC->using_directives_begin();
1310  DeclContext::udir_iterator E = StartDC->using_directives_end();
1311
1312  if (I == E) return false;
1313
1314  // We have at least added all these contexts to the queue.
1315  llvm::SmallPtrSet<DeclContext*, 8> Visited;
1316  Visited.insert(StartDC);
1317
1318  // We have not yet looked into these namespaces, much less added
1319  // their "using-children" to the queue.
1320  SmallVector<NamespaceDecl*, 8> Queue;
1321
1322  // We have already looked into the initial namespace; seed the queue
1323  // with its using-children.
1324  for (; I != E; ++I) {
1325    NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
1326    if (Visited.insert(ND))
1327      Queue.push_back(ND);
1328  }
1329
1330  // The easiest way to implement the restriction in [namespace.qual]p5
1331  // is to check whether any of the individual results found a tag
1332  // and, if so, to declare an ambiguity if the final result is not
1333  // a tag.
1334  bool FoundTag = false;
1335  bool FoundNonTag = false;
1336
1337  LookupResult LocalR(LookupResult::Temporary, R);
1338
1339  bool Found = false;
1340  while (!Queue.empty()) {
1341    NamespaceDecl *ND = Queue.back();
1342    Queue.pop_back();
1343
1344    // We go through some convolutions here to avoid copying results
1345    // between LookupResults.
1346    bool UseLocal = !R.empty();
1347    LookupResult &DirectR = UseLocal ? LocalR : R;
1348    bool FoundDirect = LookupDirect(S, DirectR, ND);
1349
1350    if (FoundDirect) {
1351      // First do any local hiding.
1352      DirectR.resolveKind();
1353
1354      // If the local result is a tag, remember that.
1355      if (DirectR.isSingleTagDecl())
1356        FoundTag = true;
1357      else
1358        FoundNonTag = true;
1359
1360      // Append the local results to the total results if necessary.
1361      if (UseLocal) {
1362        R.addAllDecls(LocalR);
1363        LocalR.clear();
1364      }
1365    }
1366
1367    // If we find names in this namespace, ignore its using directives.
1368    if (FoundDirect) {
1369      Found = true;
1370      continue;
1371    }
1372
1373    for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1374      NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1375      if (Visited.insert(Nom))
1376        Queue.push_back(Nom);
1377    }
1378  }
1379
1380  if (Found) {
1381    if (FoundTag && FoundNonTag)
1382      R.setAmbiguousQualifiedTagHiding();
1383    else
1384      R.resolveKind();
1385  }
1386
1387  return Found;
1388}
1389
1390/// \brief Callback that looks for any member of a class with the given name.
1391static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1392                            CXXBasePath &Path,
1393                            void *Name) {
1394  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1395
1396  DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1397  Path.Decls = BaseRecord->lookup(N);
1398  return !Path.Decls.empty();
1399}
1400
1401/// \brief Determine whether the given set of member declarations contains only
1402/// static members, nested types, and enumerators.
1403template<typename InputIterator>
1404static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1405  Decl *D = (*First)->getUnderlyingDecl();
1406  if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1407    return true;
1408
1409  if (isa<CXXMethodDecl>(D)) {
1410    // Determine whether all of the methods are static.
1411    bool AllMethodsAreStatic = true;
1412    for(; First != Last; ++First) {
1413      D = (*First)->getUnderlyingDecl();
1414
1415      if (!isa<CXXMethodDecl>(D)) {
1416        assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1417        break;
1418      }
1419
1420      if (!cast<CXXMethodDecl>(D)->isStatic()) {
1421        AllMethodsAreStatic = false;
1422        break;
1423      }
1424    }
1425
1426    if (AllMethodsAreStatic)
1427      return true;
1428  }
1429
1430  return false;
1431}
1432
1433/// \brief Perform qualified name lookup into a given context.
1434///
1435/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1436/// names when the context of those names is explicit specified, e.g.,
1437/// "std::vector" or "x->member", or as part of unqualified name lookup.
1438///
1439/// Different lookup criteria can find different names. For example, a
1440/// particular scope can have both a struct and a function of the same
1441/// name, and each can be found by certain lookup criteria. For more
1442/// information about lookup criteria, see the documentation for the
1443/// class LookupCriteria.
1444///
1445/// \param R captures both the lookup criteria and any lookup results found.
1446///
1447/// \param LookupCtx The context in which qualified name lookup will
1448/// search. If the lookup criteria permits, name lookup may also search
1449/// in the parent contexts or (for C++ classes) base classes.
1450///
1451/// \param InUnqualifiedLookup true if this is qualified name lookup that
1452/// occurs as part of unqualified name lookup.
1453///
1454/// \returns true if lookup succeeded, false if it failed.
1455bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1456                               bool InUnqualifiedLookup) {
1457  assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1458
1459  if (!R.getLookupName())
1460    return false;
1461
1462  // Make sure that the declaration context is complete.
1463  assert((!isa<TagDecl>(LookupCtx) ||
1464          LookupCtx->isDependentContext() ||
1465          cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
1466          cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
1467         "Declaration context must already be complete!");
1468
1469  // Perform qualified name lookup into the LookupCtx.
1470  if (LookupDirect(*this, R, LookupCtx)) {
1471    R.resolveKind();
1472    if (isa<CXXRecordDecl>(LookupCtx))
1473      R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1474    return true;
1475  }
1476
1477  // Don't descend into implied contexts for redeclarations.
1478  // C++98 [namespace.qual]p6:
1479  //   In a declaration for a namespace member in which the
1480  //   declarator-id is a qualified-id, given that the qualified-id
1481  //   for the namespace member has the form
1482  //     nested-name-specifier unqualified-id
1483  //   the unqualified-id shall name a member of the namespace
1484  //   designated by the nested-name-specifier.
1485  // See also [class.mfct]p5 and [class.static.data]p2.
1486  if (R.isForRedeclaration())
1487    return false;
1488
1489  // If this is a namespace, look it up in the implied namespaces.
1490  if (LookupCtx->isFileContext())
1491    return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1492
1493  // If this isn't a C++ class, we aren't allowed to look into base
1494  // classes, we're done.
1495  CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1496  if (!LookupRec || !LookupRec->getDefinition())
1497    return false;
1498
1499  // If we're performing qualified name lookup into a dependent class,
1500  // then we are actually looking into a current instantiation. If we have any
1501  // dependent base classes, then we either have to delay lookup until
1502  // template instantiation time (at which point all bases will be available)
1503  // or we have to fail.
1504  if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1505      LookupRec->hasAnyDependentBases()) {
1506    R.setNotFoundInCurrentInstantiation();
1507    return false;
1508  }
1509
1510  // Perform lookup into our base classes.
1511  CXXBasePaths Paths;
1512  Paths.setOrigin(LookupRec);
1513
1514  // Look for this member in our base classes
1515  CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1516  switch (R.getLookupKind()) {
1517    case LookupObjCImplicitSelfParam:
1518    case LookupOrdinaryName:
1519    case LookupMemberName:
1520    case LookupRedeclarationWithLinkage:
1521      BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1522      break;
1523
1524    case LookupTagName:
1525      BaseCallback = &CXXRecordDecl::FindTagMember;
1526      break;
1527
1528    case LookupAnyName:
1529      BaseCallback = &LookupAnyMember;
1530      break;
1531
1532    case LookupUsingDeclName:
1533      // This lookup is for redeclarations only.
1534
1535    case LookupOperatorName:
1536    case LookupNamespaceName:
1537    case LookupObjCProtocolName:
1538    case LookupLabel:
1539      // These lookups will never find a member in a C++ class (or base class).
1540      return false;
1541
1542    case LookupNestedNameSpecifierName:
1543      BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1544      break;
1545  }
1546
1547  if (!LookupRec->lookupInBases(BaseCallback,
1548                                R.getLookupName().getAsOpaquePtr(), Paths))
1549    return false;
1550
1551  R.setNamingClass(LookupRec);
1552
1553  // C++ [class.member.lookup]p2:
1554  //   [...] If the resulting set of declarations are not all from
1555  //   sub-objects of the same type, or the set has a nonstatic member
1556  //   and includes members from distinct sub-objects, there is an
1557  //   ambiguity and the program is ill-formed. Otherwise that set is
1558  //   the result of the lookup.
1559  QualType SubobjectType;
1560  int SubobjectNumber = 0;
1561  AccessSpecifier SubobjectAccess = AS_none;
1562
1563  for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1564       Path != PathEnd; ++Path) {
1565    const CXXBasePathElement &PathElement = Path->back();
1566
1567    // Pick the best (i.e. most permissive i.e. numerically lowest) access
1568    // across all paths.
1569    SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1570
1571    // Determine whether we're looking at a distinct sub-object or not.
1572    if (SubobjectType.isNull()) {
1573      // This is the first subobject we've looked at. Record its type.
1574      SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1575      SubobjectNumber = PathElement.SubobjectNumber;
1576      continue;
1577    }
1578
1579    if (SubobjectType
1580                 != Context.getCanonicalType(PathElement.Base->getType())) {
1581      // We found members of the given name in two subobjects of
1582      // different types. If the declaration sets aren't the same, this
1583      // this lookup is ambiguous.
1584      if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
1585        CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1586        DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1587        DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
1588
1589        while (FirstD != FirstPath->Decls.end() &&
1590               CurrentD != Path->Decls.end()) {
1591         if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1592             (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1593           break;
1594
1595          ++FirstD;
1596          ++CurrentD;
1597        }
1598
1599        if (FirstD == FirstPath->Decls.end() &&
1600            CurrentD == Path->Decls.end())
1601          continue;
1602      }
1603
1604      R.setAmbiguousBaseSubobjectTypes(Paths);
1605      return true;
1606    }
1607
1608    if (SubobjectNumber != PathElement.SubobjectNumber) {
1609      // We have a different subobject of the same type.
1610
1611      // C++ [class.member.lookup]p5:
1612      //   A static member, a nested type or an enumerator defined in
1613      //   a base class T can unambiguously be found even if an object
1614      //   has more than one base class subobject of type T.
1615      if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
1616        continue;
1617
1618      // We have found a nonstatic member name in multiple, distinct
1619      // subobjects. Name lookup is ambiguous.
1620      R.setAmbiguousBaseSubobjects(Paths);
1621      return true;
1622    }
1623  }
1624
1625  // Lookup in a base class succeeded; return these results.
1626
1627  DeclContext::lookup_result DR = Paths.front().Decls;
1628  for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
1629    NamedDecl *D = *I;
1630    AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1631                                                    D->getAccess());
1632    R.addDecl(D, AS);
1633  }
1634  R.resolveKind();
1635  return true;
1636}
1637
1638/// @brief Performs name lookup for a name that was parsed in the
1639/// source code, and may contain a C++ scope specifier.
1640///
1641/// This routine is a convenience routine meant to be called from
1642/// contexts that receive a name and an optional C++ scope specifier
1643/// (e.g., "N::M::x"). It will then perform either qualified or
1644/// unqualified name lookup (with LookupQualifiedName or LookupName,
1645/// respectively) on the given name and return those results.
1646///
1647/// @param S        The scope from which unqualified name lookup will
1648/// begin.
1649///
1650/// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
1651///
1652/// @param EnteringContext Indicates whether we are going to enter the
1653/// context of the scope-specifier SS (if present).
1654///
1655/// @returns True if any decls were found (but possibly ambiguous)
1656bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1657                            bool AllowBuiltinCreation, bool EnteringContext) {
1658  if (SS && SS->isInvalid()) {
1659    // When the scope specifier is invalid, don't even look for
1660    // anything.
1661    return false;
1662  }
1663
1664  if (SS && SS->isSet()) {
1665    if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1666      // We have resolved the scope specifier to a particular declaration
1667      // contex, and will perform name lookup in that context.
1668      if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1669        return false;
1670
1671      R.setContextRange(SS->getRange());
1672      return LookupQualifiedName(R, DC);
1673    }
1674
1675    // We could not resolve the scope specified to a specific declaration
1676    // context, which means that SS refers to an unknown specialization.
1677    // Name lookup can't find anything in this case.
1678    R.setNotFoundInCurrentInstantiation();
1679    R.setContextRange(SS->getRange());
1680    return false;
1681  }
1682
1683  // Perform unqualified name lookup starting in the given scope.
1684  return LookupName(R, S, AllowBuiltinCreation);
1685}
1686
1687
1688/// \brief Produce a diagnostic describing the ambiguity that resulted
1689/// from name lookup.
1690///
1691/// \param Result The result of the ambiguous lookup to be diagnosed.
1692///
1693/// \returns true
1694bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1695  assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1696
1697  DeclarationName Name = Result.getLookupName();
1698  SourceLocation NameLoc = Result.getNameLoc();
1699  SourceRange LookupRange = Result.getContextRange();
1700
1701  switch (Result.getAmbiguityKind()) {
1702  case LookupResult::AmbiguousBaseSubobjects: {
1703    CXXBasePaths *Paths = Result.getBasePaths();
1704    QualType SubobjectType = Paths->front().back().Base->getType();
1705    Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1706      << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1707      << LookupRange;
1708
1709    DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
1710    while (isa<CXXMethodDecl>(*Found) &&
1711           cast<CXXMethodDecl>(*Found)->isStatic())
1712      ++Found;
1713
1714    Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1715
1716    return true;
1717  }
1718
1719  case LookupResult::AmbiguousBaseSubobjectTypes: {
1720    Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1721      << Name << LookupRange;
1722
1723    CXXBasePaths *Paths = Result.getBasePaths();
1724    std::set<Decl *> DeclsPrinted;
1725    for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1726                                      PathEnd = Paths->end();
1727         Path != PathEnd; ++Path) {
1728      Decl *D = Path->Decls.front();
1729      if (DeclsPrinted.insert(D).second)
1730        Diag(D->getLocation(), diag::note_ambiguous_member_found);
1731    }
1732
1733    return true;
1734  }
1735
1736  case LookupResult::AmbiguousTagHiding: {
1737    Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1738
1739    llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1740
1741    LookupResult::iterator DI, DE = Result.end();
1742    for (DI = Result.begin(); DI != DE; ++DI)
1743      if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1744        TagDecls.insert(TD);
1745        Diag(TD->getLocation(), diag::note_hidden_tag);
1746      }
1747
1748    for (DI = Result.begin(); DI != DE; ++DI)
1749      if (!isa<TagDecl>(*DI))
1750        Diag((*DI)->getLocation(), diag::note_hiding_object);
1751
1752    // For recovery purposes, go ahead and implement the hiding.
1753    LookupResult::Filter F = Result.makeFilter();
1754    while (F.hasNext()) {
1755      if (TagDecls.count(F.next()))
1756        F.erase();
1757    }
1758    F.done();
1759
1760    return true;
1761  }
1762
1763  case LookupResult::AmbiguousReference: {
1764    Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1765
1766    LookupResult::iterator DI = Result.begin(), DE = Result.end();
1767    for (; DI != DE; ++DI)
1768      Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1769
1770    return true;
1771  }
1772  }
1773
1774  llvm_unreachable("unknown ambiguity kind");
1775}
1776
1777namespace {
1778  struct AssociatedLookup {
1779    AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
1780                     Sema::AssociatedNamespaceSet &Namespaces,
1781                     Sema::AssociatedClassSet &Classes)
1782      : S(S), Namespaces(Namespaces), Classes(Classes),
1783        InstantiationLoc(InstantiationLoc) {
1784    }
1785
1786    Sema &S;
1787    Sema::AssociatedNamespaceSet &Namespaces;
1788    Sema::AssociatedClassSet &Classes;
1789    SourceLocation InstantiationLoc;
1790  };
1791}
1792
1793static void
1794addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1795
1796static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1797                                      DeclContext *Ctx) {
1798  // Add the associated namespace for this class.
1799
1800  // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1801  // be a locally scoped record.
1802
1803  // We skip out of inline namespaces. The innermost non-inline namespace
1804  // contains all names of all its nested inline namespaces anyway, so we can
1805  // replace the entire inline namespace tree with its root.
1806  while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1807         Ctx->isInlineNamespace())
1808    Ctx = Ctx->getParent();
1809
1810  if (Ctx->isFileContext())
1811    Namespaces.insert(Ctx->getPrimaryContext());
1812}
1813
1814// \brief Add the associated classes and namespaces for argument-dependent
1815// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1816static void
1817addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1818                                  const TemplateArgument &Arg) {
1819  // C++ [basic.lookup.koenig]p2, last bullet:
1820  //   -- [...] ;
1821  switch (Arg.getKind()) {
1822    case TemplateArgument::Null:
1823      break;
1824
1825    case TemplateArgument::Type:
1826      // [...] the namespaces and classes associated with the types of the
1827      // template arguments provided for template type parameters (excluding
1828      // template template parameters)
1829      addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1830      break;
1831
1832    case TemplateArgument::Template:
1833    case TemplateArgument::TemplateExpansion: {
1834      // [...] the namespaces in which any template template arguments are
1835      // defined; and the classes in which any member templates used as
1836      // template template arguments are defined.
1837      TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
1838      if (ClassTemplateDecl *ClassTemplate
1839                 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1840        DeclContext *Ctx = ClassTemplate->getDeclContext();
1841        if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1842          Result.Classes.insert(EnclosingClass);
1843        // Add the associated namespace for this class.
1844        CollectEnclosingNamespace(Result.Namespaces, Ctx);
1845      }
1846      break;
1847    }
1848
1849    case TemplateArgument::Declaration:
1850    case TemplateArgument::Integral:
1851    case TemplateArgument::Expression:
1852    case TemplateArgument::NullPtr:
1853      // [Note: non-type template arguments do not contribute to the set of
1854      //  associated namespaces. ]
1855      break;
1856
1857    case TemplateArgument::Pack:
1858      for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1859                                        PEnd = Arg.pack_end();
1860           P != PEnd; ++P)
1861        addAssociatedClassesAndNamespaces(Result, *P);
1862      break;
1863  }
1864}
1865
1866// \brief Add the associated classes and namespaces for
1867// argument-dependent lookup with an argument of class type
1868// (C++ [basic.lookup.koenig]p2).
1869static void
1870addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1871                                  CXXRecordDecl *Class) {
1872
1873  // Just silently ignore anything whose name is __va_list_tag.
1874  if (Class->getDeclName() == Result.S.VAListTagName)
1875    return;
1876
1877  // C++ [basic.lookup.koenig]p2:
1878  //   [...]
1879  //     -- If T is a class type (including unions), its associated
1880  //        classes are: the class itself; the class of which it is a
1881  //        member, if any; and its direct and indirect base
1882  //        classes. Its associated namespaces are the namespaces in
1883  //        which its associated classes are defined.
1884
1885  // Add the class of which it is a member, if any.
1886  DeclContext *Ctx = Class->getDeclContext();
1887  if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1888    Result.Classes.insert(EnclosingClass);
1889  // Add the associated namespace for this class.
1890  CollectEnclosingNamespace(Result.Namespaces, Ctx);
1891
1892  // Add the class itself. If we've already seen this class, we don't
1893  // need to visit base classes.
1894  if (!Result.Classes.insert(Class))
1895    return;
1896
1897  // -- If T is a template-id, its associated namespaces and classes are
1898  //    the namespace in which the template is defined; for member
1899  //    templates, the member template's class; the namespaces and classes
1900  //    associated with the types of the template arguments provided for
1901  //    template type parameters (excluding template template parameters); the
1902  //    namespaces in which any template template arguments are defined; and
1903  //    the classes in which any member templates used as template template
1904  //    arguments are defined. [Note: non-type template arguments do not
1905  //    contribute to the set of associated namespaces. ]
1906  if (ClassTemplateSpecializationDecl *Spec
1907        = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1908    DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1909    if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1910      Result.Classes.insert(EnclosingClass);
1911    // Add the associated namespace for this class.
1912    CollectEnclosingNamespace(Result.Namespaces, Ctx);
1913
1914    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1915    for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1916      addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
1917  }
1918
1919  // Only recurse into base classes for complete types.
1920  if (!Class->hasDefinition()) {
1921    QualType type = Result.S.Context.getTypeDeclType(Class);
1922    if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
1923                                     /*no diagnostic*/ 0))
1924      return;
1925  }
1926
1927  // Add direct and indirect base classes along with their associated
1928  // namespaces.
1929  SmallVector<CXXRecordDecl *, 32> Bases;
1930  Bases.push_back(Class);
1931  while (!Bases.empty()) {
1932    // Pop this class off the stack.
1933    Class = Bases.back();
1934    Bases.pop_back();
1935
1936    // Visit the base classes.
1937    for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1938                                         BaseEnd = Class->bases_end();
1939         Base != BaseEnd; ++Base) {
1940      const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1941      // In dependent contexts, we do ADL twice, and the first time around,
1942      // the base type might be a dependent TemplateSpecializationType, or a
1943      // TemplateTypeParmType. If that happens, simply ignore it.
1944      // FIXME: If we want to support export, we probably need to add the
1945      // namespace of the template in a TemplateSpecializationType, or even
1946      // the classes and namespaces of known non-dependent arguments.
1947      if (!BaseType)
1948        continue;
1949      CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1950      if (Result.Classes.insert(BaseDecl)) {
1951        // Find the associated namespace for this base class.
1952        DeclContext *BaseCtx = BaseDecl->getDeclContext();
1953        CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
1954
1955        // Make sure we visit the bases of this base class.
1956        if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1957          Bases.push_back(BaseDecl);
1958      }
1959    }
1960  }
1961}
1962
1963// \brief Add the associated classes and namespaces for
1964// argument-dependent lookup with an argument of type T
1965// (C++ [basic.lookup.koenig]p2).
1966static void
1967addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
1968  // C++ [basic.lookup.koenig]p2:
1969  //
1970  //   For each argument type T in the function call, there is a set
1971  //   of zero or more associated namespaces and a set of zero or more
1972  //   associated classes to be considered. The sets of namespaces and
1973  //   classes is determined entirely by the types of the function
1974  //   arguments (and the namespace of any template template
1975  //   argument). Typedef names and using-declarations used to specify
1976  //   the types do not contribute to this set. The sets of namespaces
1977  //   and classes are determined in the following way:
1978
1979  SmallVector<const Type *, 16> Queue;
1980  const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1981
1982  while (true) {
1983    switch (T->getTypeClass()) {
1984
1985#define TYPE(Class, Base)
1986#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1987#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1988#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1989#define ABSTRACT_TYPE(Class, Base)
1990#include "clang/AST/TypeNodes.def"
1991      // T is canonical.  We can also ignore dependent types because
1992      // we don't need to do ADL at the definition point, but if we
1993      // wanted to implement template export (or if we find some other
1994      // use for associated classes and namespaces...) this would be
1995      // wrong.
1996      break;
1997
1998    //    -- If T is a pointer to U or an array of U, its associated
1999    //       namespaces and classes are those associated with U.
2000    case Type::Pointer:
2001      T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2002      continue;
2003    case Type::ConstantArray:
2004    case Type::IncompleteArray:
2005    case Type::VariableArray:
2006      T = cast<ArrayType>(T)->getElementType().getTypePtr();
2007      continue;
2008
2009    //     -- If T is a fundamental type, its associated sets of
2010    //        namespaces and classes are both empty.
2011    case Type::Builtin:
2012      break;
2013
2014    //     -- If T is a class type (including unions), its associated
2015    //        classes are: the class itself; the class of which it is a
2016    //        member, if any; and its direct and indirect base
2017    //        classes. Its associated namespaces are the namespaces in
2018    //        which its associated classes are defined.
2019    case Type::Record: {
2020      CXXRecordDecl *Class
2021        = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2022      addAssociatedClassesAndNamespaces(Result, Class);
2023      break;
2024    }
2025
2026    //     -- If T is an enumeration type, its associated namespace is
2027    //        the namespace in which it is defined. If it is class
2028    //        member, its associated class is the member's class; else
2029    //        it has no associated class.
2030    case Type::Enum: {
2031      EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2032
2033      DeclContext *Ctx = Enum->getDeclContext();
2034      if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2035        Result.Classes.insert(EnclosingClass);
2036
2037      // Add the associated namespace for this class.
2038      CollectEnclosingNamespace(Result.Namespaces, Ctx);
2039
2040      break;
2041    }
2042
2043    //     -- If T is a function type, its associated namespaces and
2044    //        classes are those associated with the function parameter
2045    //        types and those associated with the return type.
2046    case Type::FunctionProto: {
2047      const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2048      for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2049                                             ArgEnd = Proto->arg_type_end();
2050             Arg != ArgEnd; ++Arg)
2051        Queue.push_back(Arg->getTypePtr());
2052      // fallthrough
2053    }
2054    case Type::FunctionNoProto: {
2055      const FunctionType *FnType = cast<FunctionType>(T);
2056      T = FnType->getResultType().getTypePtr();
2057      continue;
2058    }
2059
2060    //     -- If T is a pointer to a member function of a class X, its
2061    //        associated namespaces and classes are those associated
2062    //        with the function parameter types and return type,
2063    //        together with those associated with X.
2064    //
2065    //     -- If T is a pointer to a data member of class X, its
2066    //        associated namespaces and classes are those associated
2067    //        with the member type together with those associated with
2068    //        X.
2069    case Type::MemberPointer: {
2070      const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2071
2072      // Queue up the class type into which this points.
2073      Queue.push_back(MemberPtr->getClass());
2074
2075      // And directly continue with the pointee type.
2076      T = MemberPtr->getPointeeType().getTypePtr();
2077      continue;
2078    }
2079
2080    // As an extension, treat this like a normal pointer.
2081    case Type::BlockPointer:
2082      T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2083      continue;
2084
2085    // References aren't covered by the standard, but that's such an
2086    // obvious defect that we cover them anyway.
2087    case Type::LValueReference:
2088    case Type::RValueReference:
2089      T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2090      continue;
2091
2092    // These are fundamental types.
2093    case Type::Vector:
2094    case Type::ExtVector:
2095    case Type::Complex:
2096      break;
2097
2098    // Non-deduced auto types only get here for error cases.
2099    case Type::Auto:
2100      break;
2101
2102    // If T is an Objective-C object or interface type, or a pointer to an
2103    // object or interface type, the associated namespace is the global
2104    // namespace.
2105    case Type::ObjCObject:
2106    case Type::ObjCInterface:
2107    case Type::ObjCObjectPointer:
2108      Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2109      break;
2110
2111    // Atomic types are just wrappers; use the associations of the
2112    // contained type.
2113    case Type::Atomic:
2114      T = cast<AtomicType>(T)->getValueType().getTypePtr();
2115      continue;
2116    }
2117
2118    if (Queue.empty()) break;
2119    T = Queue.back();
2120    Queue.pop_back();
2121  }
2122}
2123
2124/// \brief Find the associated classes and namespaces for
2125/// argument-dependent lookup for a call with the given set of
2126/// arguments.
2127///
2128/// This routine computes the sets of associated classes and associated
2129/// namespaces searched by argument-dependent lookup
2130/// (C++ [basic.lookup.argdep]) for a given set of arguments.
2131void
2132Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2133                                         llvm::ArrayRef<Expr *> Args,
2134                                 AssociatedNamespaceSet &AssociatedNamespaces,
2135                                 AssociatedClassSet &AssociatedClasses) {
2136  AssociatedNamespaces.clear();
2137  AssociatedClasses.clear();
2138
2139  AssociatedLookup Result(*this, InstantiationLoc,
2140                          AssociatedNamespaces, AssociatedClasses);
2141
2142  // C++ [basic.lookup.koenig]p2:
2143  //   For each argument type T in the function call, there is a set
2144  //   of zero or more associated namespaces and a set of zero or more
2145  //   associated classes to be considered. The sets of namespaces and
2146  //   classes is determined entirely by the types of the function
2147  //   arguments (and the namespace of any template template
2148  //   argument).
2149  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2150    Expr *Arg = Args[ArgIdx];
2151
2152    if (Arg->getType() != Context.OverloadTy) {
2153      addAssociatedClassesAndNamespaces(Result, Arg->getType());
2154      continue;
2155    }
2156
2157    // [...] In addition, if the argument is the name or address of a
2158    // set of overloaded functions and/or function templates, its
2159    // associated classes and namespaces are the union of those
2160    // associated with each of the members of the set: the namespace
2161    // in which the function or function template is defined and the
2162    // classes and namespaces associated with its (non-dependent)
2163    // parameter types and return type.
2164    Arg = Arg->IgnoreParens();
2165    if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2166      if (unaryOp->getOpcode() == UO_AddrOf)
2167        Arg = unaryOp->getSubExpr();
2168
2169    UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2170    if (!ULE) continue;
2171
2172    for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2173           I != E; ++I) {
2174      // Look through any using declarations to find the underlying function.
2175      NamedDecl *Fn = (*I)->getUnderlyingDecl();
2176
2177      FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2178      if (!FDecl)
2179        FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
2180
2181      // Add the classes and namespaces associated with the parameter
2182      // types and return type of this function.
2183      addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2184    }
2185  }
2186}
2187
2188/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2189/// an acceptable non-member overloaded operator for a call whose
2190/// arguments have types T1 (and, if non-empty, T2). This routine
2191/// implements the check in C++ [over.match.oper]p3b2 concerning
2192/// enumeration types.
2193static bool
2194IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2195                                       QualType T1, QualType T2,
2196                                       ASTContext &Context) {
2197  if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2198    return true;
2199
2200  if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2201    return true;
2202
2203  const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
2204  if (Proto->getNumArgs() < 1)
2205    return false;
2206
2207  if (T1->isEnumeralType()) {
2208    QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2209    if (Context.hasSameUnqualifiedType(T1, ArgType))
2210      return true;
2211  }
2212
2213  if (Proto->getNumArgs() < 2)
2214    return false;
2215
2216  if (!T2.isNull() && T2->isEnumeralType()) {
2217    QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2218    if (Context.hasSameUnqualifiedType(T2, ArgType))
2219      return true;
2220  }
2221
2222  return false;
2223}
2224
2225NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2226                                  SourceLocation Loc,
2227                                  LookupNameKind NameKind,
2228                                  RedeclarationKind Redecl) {
2229  LookupResult R(*this, Name, Loc, NameKind, Redecl);
2230  LookupName(R, S);
2231  return R.getAsSingle<NamedDecl>();
2232}
2233
2234/// \brief Find the protocol with the given name, if any.
2235ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2236                                       SourceLocation IdLoc,
2237                                       RedeclarationKind Redecl) {
2238  Decl *D = LookupSingleName(TUScope, II, IdLoc,
2239                             LookupObjCProtocolName, Redecl);
2240  return cast_or_null<ObjCProtocolDecl>(D);
2241}
2242
2243void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2244                                        QualType T1, QualType T2,
2245                                        UnresolvedSetImpl &Functions) {
2246  // C++ [over.match.oper]p3:
2247  //     -- The set of non-member candidates is the result of the
2248  //        unqualified lookup of operator@ in the context of the
2249  //        expression according to the usual rules for name lookup in
2250  //        unqualified function calls (3.4.2) except that all member
2251  //        functions are ignored. However, if no operand has a class
2252  //        type, only those non-member functions in the lookup set
2253  //        that have a first parameter of type T1 or "reference to
2254  //        (possibly cv-qualified) T1", when T1 is an enumeration
2255  //        type, or (if there is a right operand) a second parameter
2256  //        of type T2 or "reference to (possibly cv-qualified) T2",
2257  //        when T2 is an enumeration type, are candidate functions.
2258  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2259  LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2260  LookupName(Operators, S);
2261
2262  assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2263
2264  if (Operators.empty())
2265    return;
2266
2267  for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2268       Op != OpEnd; ++Op) {
2269    NamedDecl *Found = (*Op)->getUnderlyingDecl();
2270    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
2271      if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2272        Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
2273    } else if (FunctionTemplateDecl *FunTmpl
2274                 = dyn_cast<FunctionTemplateDecl>(Found)) {
2275      // FIXME: friend operators?
2276      // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2277      // later?
2278      if (!FunTmpl->getDeclContext()->isRecord())
2279        Functions.addDecl(*Op, Op.getAccess());
2280    }
2281  }
2282}
2283
2284Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
2285                                                            CXXSpecialMember SM,
2286                                                            bool ConstArg,
2287                                                            bool VolatileArg,
2288                                                            bool RValueThis,
2289                                                            bool ConstThis,
2290                                                            bool VolatileThis) {
2291  assert(CanDeclareSpecialMemberFunction(RD) &&
2292         "doing special member lookup into record that isn't fully complete");
2293  RD = RD->getDefinition();
2294  if (RValueThis || ConstThis || VolatileThis)
2295    assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2296           "constructors and destructors always have unqualified lvalue this");
2297  if (ConstArg || VolatileArg)
2298    assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2299           "parameter-less special members can't have qualified arguments");
2300
2301  llvm::FoldingSetNodeID ID;
2302  ID.AddPointer(RD);
2303  ID.AddInteger(SM);
2304  ID.AddInteger(ConstArg);
2305  ID.AddInteger(VolatileArg);
2306  ID.AddInteger(RValueThis);
2307  ID.AddInteger(ConstThis);
2308  ID.AddInteger(VolatileThis);
2309
2310  void *InsertPoint;
2311  SpecialMemberOverloadResult *Result =
2312    SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2313
2314  // This was already cached
2315  if (Result)
2316    return Result;
2317
2318  Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2319  Result = new (Result) SpecialMemberOverloadResult(ID);
2320  SpecialMemberCache.InsertNode(Result, InsertPoint);
2321
2322  if (SM == CXXDestructor) {
2323    if (RD->needsImplicitDestructor())
2324      DeclareImplicitDestructor(RD);
2325    CXXDestructorDecl *DD = RD->getDestructor();
2326    assert(DD && "record without a destructor");
2327    Result->setMethod(DD);
2328    Result->setKind(DD->isDeleted() ?
2329                    SpecialMemberOverloadResult::NoMemberOrDeleted :
2330                    SpecialMemberOverloadResult::Success);
2331    return Result;
2332  }
2333
2334  // Prepare for overload resolution. Here we construct a synthetic argument
2335  // if necessary and make sure that implicit functions are declared.
2336  CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2337  DeclarationName Name;
2338  Expr *Arg = 0;
2339  unsigned NumArgs;
2340
2341  QualType ArgType = CanTy;
2342  ExprValueKind VK = VK_LValue;
2343
2344  if (SM == CXXDefaultConstructor) {
2345    Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2346    NumArgs = 0;
2347    if (RD->needsImplicitDefaultConstructor())
2348      DeclareImplicitDefaultConstructor(RD);
2349  } else {
2350    if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2351      Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2352      if (RD->needsImplicitCopyConstructor())
2353        DeclareImplicitCopyConstructor(RD);
2354      if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
2355        DeclareImplicitMoveConstructor(RD);
2356    } else {
2357      Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2358      if (RD->needsImplicitCopyAssignment())
2359        DeclareImplicitCopyAssignment(RD);
2360      if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
2361        DeclareImplicitMoveAssignment(RD);
2362    }
2363
2364    if (ConstArg)
2365      ArgType.addConst();
2366    if (VolatileArg)
2367      ArgType.addVolatile();
2368
2369    // This isn't /really/ specified by the standard, but it's implied
2370    // we should be working from an RValue in the case of move to ensure
2371    // that we prefer to bind to rvalue references, and an LValue in the
2372    // case of copy to ensure we don't bind to rvalue references.
2373    // Possibly an XValue is actually correct in the case of move, but
2374    // there is no semantic difference for class types in this restricted
2375    // case.
2376    if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2377      VK = VK_LValue;
2378    else
2379      VK = VK_RValue;
2380  }
2381
2382  OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2383
2384  if (SM != CXXDefaultConstructor) {
2385    NumArgs = 1;
2386    Arg = &FakeArg;
2387  }
2388
2389  // Create the object argument
2390  QualType ThisTy = CanTy;
2391  if (ConstThis)
2392    ThisTy.addConst();
2393  if (VolatileThis)
2394    ThisTy.addVolatile();
2395  Expr::Classification Classification =
2396    OpaqueValueExpr(SourceLocation(), ThisTy,
2397                    RValueThis ? VK_RValue : VK_LValue).Classify(Context);
2398
2399  // Now we perform lookup on the name we computed earlier and do overload
2400  // resolution. Lookup is only performed directly into the class since there
2401  // will always be a (possibly implicit) declaration to shadow any others.
2402  OverloadCandidateSet OCS((SourceLocation()));
2403  DeclContext::lookup_result R = RD->lookup(Name);
2404
2405  assert(!R.empty() &&
2406         "lookup for a constructor or assignment operator was empty");
2407  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
2408    Decl *Cand = *I;
2409
2410    if (Cand->isInvalidDecl())
2411      continue;
2412
2413    if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2414      // FIXME: [namespace.udecl]p15 says that we should only consider a
2415      // using declaration here if it does not match a declaration in the
2416      // derived class. We do not implement this correctly in other cases
2417      // either.
2418      Cand = U->getTargetDecl();
2419
2420      if (Cand->isInvalidDecl())
2421        continue;
2422    }
2423
2424    if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
2425      if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2426        AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
2427                           Classification, llvm::makeArrayRef(&Arg, NumArgs),
2428                           OCS, true);
2429      else
2430        AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2431                             llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2432    } else if (FunctionTemplateDecl *Tmpl =
2433                 dyn_cast<FunctionTemplateDecl>(Cand)) {
2434      if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2435        AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2436                                   RD, 0, ThisTy, Classification,
2437                                   llvm::makeArrayRef(&Arg, NumArgs),
2438                                   OCS, true);
2439      else
2440        AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2441                                     0, llvm::makeArrayRef(&Arg, NumArgs),
2442                                     OCS, true);
2443    } else {
2444      assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
2445    }
2446  }
2447
2448  OverloadCandidateSet::iterator Best;
2449  switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2450    case OR_Success:
2451      Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2452      Result->setKind(SpecialMemberOverloadResult::Success);
2453      break;
2454
2455    case OR_Deleted:
2456      Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2457      Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2458      break;
2459
2460    case OR_Ambiguous:
2461      Result->setMethod(0);
2462      Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2463      break;
2464
2465    case OR_No_Viable_Function:
2466      Result->setMethod(0);
2467      Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2468      break;
2469  }
2470
2471  return Result;
2472}
2473
2474/// \brief Look up the default constructor for the given class.
2475CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
2476  SpecialMemberOverloadResult *Result =
2477    LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2478                        false, false);
2479
2480  return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2481}
2482
2483/// \brief Look up the copying constructor for the given class.
2484CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2485                                                   unsigned Quals) {
2486  assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2487         "non-const, non-volatile qualifiers for copy ctor arg");
2488  SpecialMemberOverloadResult *Result =
2489    LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2490                        Quals & Qualifiers::Volatile, false, false, false);
2491
2492  return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2493}
2494
2495/// \brief Look up the moving constructor for the given class.
2496CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2497                                                  unsigned Quals) {
2498  SpecialMemberOverloadResult *Result =
2499    LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2500                        Quals & Qualifiers::Volatile, false, false, false);
2501
2502  return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2503}
2504
2505/// \brief Look up the constructors for the given class.
2506DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2507  // If the implicit constructors have not yet been declared, do so now.
2508  if (CanDeclareSpecialMemberFunction(Class)) {
2509    if (Class->needsImplicitDefaultConstructor())
2510      DeclareImplicitDefaultConstructor(Class);
2511    if (Class->needsImplicitCopyConstructor())
2512      DeclareImplicitCopyConstructor(Class);
2513    if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
2514      DeclareImplicitMoveConstructor(Class);
2515  }
2516
2517  CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2518  DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2519  return Class->lookup(Name);
2520}
2521
2522/// \brief Look up the copying assignment operator for the given class.
2523CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2524                                             unsigned Quals, bool RValueThis,
2525                                             unsigned ThisQuals) {
2526  assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2527         "non-const, non-volatile qualifiers for copy assignment arg");
2528  assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2529         "non-const, non-volatile qualifiers for copy assignment this");
2530  SpecialMemberOverloadResult *Result =
2531    LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2532                        Quals & Qualifiers::Volatile, RValueThis,
2533                        ThisQuals & Qualifiers::Const,
2534                        ThisQuals & Qualifiers::Volatile);
2535
2536  return Result->getMethod();
2537}
2538
2539/// \brief Look up the moving assignment operator for the given class.
2540CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2541                                            unsigned Quals,
2542                                            bool RValueThis,
2543                                            unsigned ThisQuals) {
2544  assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2545         "non-const, non-volatile qualifiers for copy assignment this");
2546  SpecialMemberOverloadResult *Result =
2547    LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2548                        Quals & Qualifiers::Volatile, RValueThis,
2549                        ThisQuals & Qualifiers::Const,
2550                        ThisQuals & Qualifiers::Volatile);
2551
2552  return Result->getMethod();
2553}
2554
2555/// \brief Look for the destructor of the given class.
2556///
2557/// During semantic analysis, this routine should be used in lieu of
2558/// CXXRecordDecl::getDestructor().
2559///
2560/// \returns The destructor for this class.
2561CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2562  return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2563                                                     false, false, false,
2564                                                     false, false)->getMethod());
2565}
2566
2567/// LookupLiteralOperator - Determine which literal operator should be used for
2568/// a user-defined literal, per C++11 [lex.ext].
2569///
2570/// Normal overload resolution is not used to select which literal operator to
2571/// call for a user-defined literal. Look up the provided literal operator name,
2572/// and filter the results to the appropriate set for the given argument types.
2573Sema::LiteralOperatorLookupResult
2574Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2575                            ArrayRef<QualType> ArgTys,
2576                            bool AllowRawAndTemplate) {
2577  LookupName(R, S);
2578  assert(R.getResultKind() != LookupResult::Ambiguous &&
2579         "literal operator lookup can't be ambiguous");
2580
2581  // Filter the lookup results appropriately.
2582  LookupResult::Filter F = R.makeFilter();
2583
2584  bool FoundTemplate = false;
2585  bool FoundRaw = false;
2586  bool FoundExactMatch = false;
2587
2588  while (F.hasNext()) {
2589    Decl *D = F.next();
2590    if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2591      D = USD->getTargetDecl();
2592
2593    bool IsTemplate = isa<FunctionTemplateDecl>(D);
2594    bool IsRaw = false;
2595    bool IsExactMatch = false;
2596
2597    // If the declaration we found is invalid, skip it.
2598    if (D->isInvalidDecl()) {
2599      F.erase();
2600      continue;
2601    }
2602
2603    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2604      if (FD->getNumParams() == 1 &&
2605          FD->getParamDecl(0)->getType()->getAs<PointerType>())
2606        IsRaw = true;
2607      else if (FD->getNumParams() == ArgTys.size()) {
2608        IsExactMatch = true;
2609        for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2610          QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2611          if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2612            IsExactMatch = false;
2613            break;
2614          }
2615        }
2616      }
2617    }
2618
2619    if (IsExactMatch) {
2620      FoundExactMatch = true;
2621      AllowRawAndTemplate = false;
2622      if (FoundRaw || FoundTemplate) {
2623        // Go through again and remove the raw and template decls we've
2624        // already found.
2625        F.restart();
2626        FoundRaw = FoundTemplate = false;
2627      }
2628    } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2629      FoundTemplate |= IsTemplate;
2630      FoundRaw |= IsRaw;
2631    } else {
2632      F.erase();
2633    }
2634  }
2635
2636  F.done();
2637
2638  // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2639  // parameter type, that is used in preference to a raw literal operator
2640  // or literal operator template.
2641  if (FoundExactMatch)
2642    return LOLR_Cooked;
2643
2644  // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2645  // operator template, but not both.
2646  if (FoundRaw && FoundTemplate) {
2647    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2648    for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2649      Decl *D = *I;
2650      if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2651        D = USD->getTargetDecl();
2652      if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2653        D = FunTmpl->getTemplatedDecl();
2654      NoteOverloadCandidate(cast<FunctionDecl>(D));
2655    }
2656    return LOLR_Error;
2657  }
2658
2659  if (FoundRaw)
2660    return LOLR_Raw;
2661
2662  if (FoundTemplate)
2663    return LOLR_Template;
2664
2665  // Didn't find anything we could use.
2666  Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2667    << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2668    << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2669  return LOLR_Error;
2670}
2671
2672void ADLResult::insert(NamedDecl *New) {
2673  NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2674
2675  // If we haven't yet seen a decl for this key, or the last decl
2676  // was exactly this one, we're done.
2677  if (Old == 0 || Old == New) {
2678    Old = New;
2679    return;
2680  }
2681
2682  // Otherwise, decide which is a more recent redeclaration.
2683  FunctionDecl *OldFD, *NewFD;
2684  if (isa<FunctionTemplateDecl>(New)) {
2685    OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2686    NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2687  } else {
2688    OldFD = cast<FunctionDecl>(Old);
2689    NewFD = cast<FunctionDecl>(New);
2690  }
2691
2692  FunctionDecl *Cursor = NewFD;
2693  while (true) {
2694    Cursor = Cursor->getPreviousDecl();
2695
2696    // If we got to the end without finding OldFD, OldFD is the newer
2697    // declaration;  leave things as they are.
2698    if (!Cursor) return;
2699
2700    // If we do find OldFD, then NewFD is newer.
2701    if (Cursor == OldFD) break;
2702
2703    // Otherwise, keep looking.
2704  }
2705
2706  Old = New;
2707}
2708
2709void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
2710                                   SourceLocation Loc,
2711                                   llvm::ArrayRef<Expr *> Args,
2712                                   ADLResult &Result) {
2713  // Find all of the associated namespaces and classes based on the
2714  // arguments we have.
2715  AssociatedNamespaceSet AssociatedNamespaces;
2716  AssociatedClassSet AssociatedClasses;
2717  FindAssociatedClassesAndNamespaces(Loc, Args,
2718                                     AssociatedNamespaces,
2719                                     AssociatedClasses);
2720
2721  QualType T1, T2;
2722  if (Operator) {
2723    T1 = Args[0]->getType();
2724    if (Args.size() >= 2)
2725      T2 = Args[1]->getType();
2726  }
2727
2728  // C++ [basic.lookup.argdep]p3:
2729  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
2730  //   and let Y be the lookup set produced by argument dependent
2731  //   lookup (defined as follows). If X contains [...] then Y is
2732  //   empty. Otherwise Y is the set of declarations found in the
2733  //   namespaces associated with the argument types as described
2734  //   below. The set of declarations found by the lookup of the name
2735  //   is the union of X and Y.
2736  //
2737  // Here, we compute Y and add its members to the overloaded
2738  // candidate set.
2739  for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
2740                                     NSEnd = AssociatedNamespaces.end();
2741       NS != NSEnd; ++NS) {
2742    //   When considering an associated namespace, the lookup is the
2743    //   same as the lookup performed when the associated namespace is
2744    //   used as a qualifier (3.4.3.2) except that:
2745    //
2746    //     -- Any using-directives in the associated namespace are
2747    //        ignored.
2748    //
2749    //     -- Any namespace-scope friend functions declared in
2750    //        associated classes are visible within their respective
2751    //        namespaces even if they are not visible during an ordinary
2752    //        lookup (11.4).
2753    DeclContext::lookup_result R = (*NS)->lookup(Name);
2754    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2755         ++I) {
2756      NamedDecl *D = *I;
2757      // If the only declaration here is an ordinary friend, consider
2758      // it only if it was declared in an associated classes.
2759      if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
2760        DeclContext *LexDC = D->getLexicalDeclContext();
2761        if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2762          continue;
2763      }
2764
2765      if (isa<UsingShadowDecl>(D))
2766        D = cast<UsingShadowDecl>(D)->getTargetDecl();
2767
2768      if (isa<FunctionDecl>(D)) {
2769        if (Operator &&
2770            !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2771                                                    T1, T2, Context))
2772          continue;
2773      } else if (!isa<FunctionTemplateDecl>(D))
2774        continue;
2775
2776      Result.insert(D);
2777    }
2778  }
2779}
2780
2781//----------------------------------------------------------------------------
2782// Search for all visible declarations.
2783//----------------------------------------------------------------------------
2784VisibleDeclConsumer::~VisibleDeclConsumer() { }
2785
2786namespace {
2787
2788class ShadowContextRAII;
2789
2790class VisibleDeclsRecord {
2791public:
2792  /// \brief An entry in the shadow map, which is optimized to store a
2793  /// single declaration (the common case) but can also store a list
2794  /// of declarations.
2795  typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
2796
2797private:
2798  /// \brief A mapping from declaration names to the declarations that have
2799  /// this name within a particular scope.
2800  typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2801
2802  /// \brief A list of shadow maps, which is used to model name hiding.
2803  std::list<ShadowMap> ShadowMaps;
2804
2805  /// \brief The declaration contexts we have already visited.
2806  llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2807
2808  friend class ShadowContextRAII;
2809
2810public:
2811  /// \brief Determine whether we have already visited this context
2812  /// (and, if not, note that we are going to visit that context now).
2813  bool visitedContext(DeclContext *Ctx) {
2814    return !VisitedContexts.insert(Ctx);
2815  }
2816
2817  bool alreadyVisitedContext(DeclContext *Ctx) {
2818    return VisitedContexts.count(Ctx);
2819  }
2820
2821  /// \brief Determine whether the given declaration is hidden in the
2822  /// current scope.
2823  ///
2824  /// \returns the declaration that hides the given declaration, or
2825  /// NULL if no such declaration exists.
2826  NamedDecl *checkHidden(NamedDecl *ND);
2827
2828  /// \brief Add a declaration to the current shadow map.
2829  void add(NamedDecl *ND) {
2830    ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2831  }
2832};
2833
2834/// \brief RAII object that records when we've entered a shadow context.
2835class ShadowContextRAII {
2836  VisibleDeclsRecord &Visible;
2837
2838  typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2839
2840public:
2841  ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2842    Visible.ShadowMaps.push_back(ShadowMap());
2843  }
2844
2845  ~ShadowContextRAII() {
2846    Visible.ShadowMaps.pop_back();
2847  }
2848};
2849
2850} // end anonymous namespace
2851
2852NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2853  // Look through using declarations.
2854  ND = ND->getUnderlyingDecl();
2855
2856  unsigned IDNS = ND->getIdentifierNamespace();
2857  std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2858  for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2859       SM != SMEnd; ++SM) {
2860    ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2861    if (Pos == SM->end())
2862      continue;
2863
2864    for (ShadowMapEntry::iterator I = Pos->second.begin(),
2865                               IEnd = Pos->second.end();
2866         I != IEnd; ++I) {
2867      // A tag declaration does not hide a non-tag declaration.
2868      if ((*I)->hasTagIdentifierNamespace() &&
2869          (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2870                   Decl::IDNS_ObjCProtocol)))
2871        continue;
2872
2873      // Protocols are in distinct namespaces from everything else.
2874      if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2875           || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2876          (*I)->getIdentifierNamespace() != IDNS)
2877        continue;
2878
2879      // Functions and function templates in the same scope overload
2880      // rather than hide.  FIXME: Look for hiding based on function
2881      // signatures!
2882      if ((*I)->isFunctionOrFunctionTemplate() &&
2883          ND->isFunctionOrFunctionTemplate() &&
2884          SM == ShadowMaps.rbegin())
2885        continue;
2886
2887      // We've found a declaration that hides this one.
2888      return *I;
2889    }
2890  }
2891
2892  return 0;
2893}
2894
2895static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2896                               bool QualifiedNameLookup,
2897                               bool InBaseClass,
2898                               VisibleDeclConsumer &Consumer,
2899                               VisibleDeclsRecord &Visited) {
2900  if (!Ctx)
2901    return;
2902
2903  // Make sure we don't visit the same context twice.
2904  if (Visited.visitedContext(Ctx->getPrimaryContext()))
2905    return;
2906
2907  if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2908    Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2909
2910  // Enumerate all of the results in this context.
2911  for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2912                                      LEnd = Ctx->lookups_end();
2913       L != LEnd; ++L) {
2914    DeclContext::lookup_result R = *L;
2915    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2916         ++I) {
2917      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
2918        if ((ND = Result.getAcceptableDecl(ND))) {
2919          Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
2920          Visited.add(ND);
2921        }
2922      }
2923    }
2924  }
2925
2926  // Traverse using directives for qualified name lookup.
2927  if (QualifiedNameLookup) {
2928    ShadowContextRAII Shadow(Visited);
2929    DeclContext::udir_iterator I, E;
2930    for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2931      LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
2932                         QualifiedNameLookup, InBaseClass, Consumer, Visited);
2933    }
2934  }
2935
2936  // Traverse the contexts of inherited C++ classes.
2937  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2938    if (!Record->hasDefinition())
2939      return;
2940
2941    for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2942                                         BEnd = Record->bases_end();
2943         B != BEnd; ++B) {
2944      QualType BaseType = B->getType();
2945
2946      // Don't look into dependent bases, because name lookup can't look
2947      // there anyway.
2948      if (BaseType->isDependentType())
2949        continue;
2950
2951      const RecordType *Record = BaseType->getAs<RecordType>();
2952      if (!Record)
2953        continue;
2954
2955      // FIXME: It would be nice to be able to determine whether referencing
2956      // a particular member would be ambiguous. For example, given
2957      //
2958      //   struct A { int member; };
2959      //   struct B { int member; };
2960      //   struct C : A, B { };
2961      //
2962      //   void f(C *c) { c->### }
2963      //
2964      // accessing 'member' would result in an ambiguity. However, we
2965      // could be smart enough to qualify the member with the base
2966      // class, e.g.,
2967      //
2968      //   c->B::member
2969      //
2970      // or
2971      //
2972      //   c->A::member
2973
2974      // Find results in this base class (and its bases).
2975      ShadowContextRAII Shadow(Visited);
2976      LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
2977                         true, Consumer, Visited);
2978    }
2979  }
2980
2981  // Traverse the contexts of Objective-C classes.
2982  if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2983    // Traverse categories.
2984    for (ObjCInterfaceDecl::visible_categories_iterator
2985           Cat = IFace->visible_categories_begin(),
2986           CatEnd = IFace->visible_categories_end();
2987         Cat != CatEnd; ++Cat) {
2988      ShadowContextRAII Shadow(Visited);
2989      LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
2990                         Consumer, Visited);
2991    }
2992
2993    // Traverse protocols.
2994    for (ObjCInterfaceDecl::all_protocol_iterator
2995         I = IFace->all_referenced_protocol_begin(),
2996         E = IFace->all_referenced_protocol_end(); I != E; ++I) {
2997      ShadowContextRAII Shadow(Visited);
2998      LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2999                         Visited);
3000    }
3001
3002    // Traverse the superclass.
3003    if (IFace->getSuperClass()) {
3004      ShadowContextRAII Shadow(Visited);
3005      LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
3006                         true, Consumer, Visited);
3007    }
3008
3009    // If there is an implementation, traverse it. We do this to find
3010    // synthesized ivars.
3011    if (IFace->getImplementation()) {
3012      ShadowContextRAII Shadow(Visited);
3013      LookupVisibleDecls(IFace->getImplementation(), Result,
3014                         QualifiedNameLookup, InBaseClass, Consumer, Visited);
3015    }
3016  } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3017    for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3018           E = Protocol->protocol_end(); I != E; ++I) {
3019      ShadowContextRAII Shadow(Visited);
3020      LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
3021                         Visited);
3022    }
3023  } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3024    for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3025           E = Category->protocol_end(); I != E; ++I) {
3026      ShadowContextRAII Shadow(Visited);
3027      LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
3028                         Visited);
3029    }
3030
3031    // If there is an implementation, traverse it.
3032    if (Category->getImplementation()) {
3033      ShadowContextRAII Shadow(Visited);
3034      LookupVisibleDecls(Category->getImplementation(), Result,
3035                         QualifiedNameLookup, true, Consumer, Visited);
3036    }
3037  }
3038}
3039
3040static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3041                               UnqualUsingDirectiveSet &UDirs,
3042                               VisibleDeclConsumer &Consumer,
3043                               VisibleDeclsRecord &Visited) {
3044  if (!S)
3045    return;
3046
3047  if (!S->getEntity() ||
3048      (!S->getParent() &&
3049       !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
3050      ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3051    // Walk through the declarations in this Scope.
3052    for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3053         D != DEnd; ++D) {
3054      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
3055        if ((ND = Result.getAcceptableDecl(ND))) {
3056          Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
3057          Visited.add(ND);
3058        }
3059    }
3060  }
3061
3062  // FIXME: C++ [temp.local]p8
3063  DeclContext *Entity = 0;
3064  if (S->getEntity()) {
3065    // Look into this scope's declaration context, along with any of its
3066    // parent lookup contexts (e.g., enclosing classes), up to the point
3067    // where we hit the context stored in the next outer scope.
3068    Entity = (DeclContext *)S->getEntity();
3069    DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
3070
3071    for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3072         Ctx = Ctx->getLookupParent()) {
3073      if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3074        if (Method->isInstanceMethod()) {
3075          // For instance methods, look for ivars in the method's interface.
3076          LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3077                                  Result.getNameLoc(), Sema::LookupMemberName);
3078          if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3079            LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
3080                               /*InBaseClass=*/false, Consumer, Visited);
3081          }
3082        }
3083
3084        // We've already performed all of the name lookup that we need
3085        // to for Objective-C methods; the next context will be the
3086        // outer scope.
3087        break;
3088      }
3089
3090      if (Ctx->isFunctionOrMethod())
3091        continue;
3092
3093      LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
3094                         /*InBaseClass=*/false, Consumer, Visited);
3095    }
3096  } else if (!S->getParent()) {
3097    // Look into the translation unit scope. We walk through the translation
3098    // unit's declaration context, because the Scope itself won't have all of
3099    // the declarations if we loaded a precompiled header.
3100    // FIXME: We would like the translation unit's Scope object to point to the
3101    // translation unit, so we don't need this special "if" branch. However,
3102    // doing so would force the normal C++ name-lookup code to look into the
3103    // translation unit decl when the IdentifierInfo chains would suffice.
3104    // Once we fix that problem (which is part of a more general "don't look
3105    // in DeclContexts unless we have to" optimization), we can eliminate this.
3106    Entity = Result.getSema().Context.getTranslationUnitDecl();
3107    LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
3108                       /*InBaseClass=*/false, Consumer, Visited);
3109  }
3110
3111  if (Entity) {
3112    // Lookup visible declarations in any namespaces found by using
3113    // directives.
3114    UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3115    llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3116    for (; UI != UEnd; ++UI)
3117      LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
3118                         Result, /*QualifiedNameLookup=*/false,
3119                         /*InBaseClass=*/false, Consumer, Visited);
3120  }
3121
3122  // Lookup names in the parent scope.
3123  ShadowContextRAII Shadow(Visited);
3124  LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3125}
3126
3127void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3128                              VisibleDeclConsumer &Consumer,
3129                              bool IncludeGlobalScope) {
3130  // Determine the set of using directives available during
3131  // unqualified name lookup.
3132  Scope *Initial = S;
3133  UnqualUsingDirectiveSet UDirs;
3134  if (getLangOpts().CPlusPlus) {
3135    // Find the first namespace or translation-unit scope.
3136    while (S && !isNamespaceOrTranslationUnitScope(S))
3137      S = S->getParent();
3138
3139    UDirs.visitScopeChain(Initial, S);
3140  }
3141  UDirs.done();
3142
3143  // Look for visible declarations.
3144  LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3145  VisibleDeclsRecord Visited;
3146  if (!IncludeGlobalScope)
3147    Visited.visitedContext(Context.getTranslationUnitDecl());
3148  ShadowContextRAII Shadow(Visited);
3149  ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3150}
3151
3152void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3153                              VisibleDeclConsumer &Consumer,
3154                              bool IncludeGlobalScope) {
3155  LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3156  VisibleDeclsRecord Visited;
3157  if (!IncludeGlobalScope)
3158    Visited.visitedContext(Context.getTranslationUnitDecl());
3159  ShadowContextRAII Shadow(Visited);
3160  ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3161                       /*InBaseClass=*/false, Consumer, Visited);
3162}
3163
3164/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3165/// If GnuLabelLoc is a valid source location, then this is a definition
3166/// of an __label__ label name, otherwise it is a normal label definition
3167/// or use.
3168LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
3169                                     SourceLocation GnuLabelLoc) {
3170  // Do a lookup to see if we have a label with this name already.
3171  NamedDecl *Res = 0;
3172
3173  if (GnuLabelLoc.isValid()) {
3174    // Local label definitions always shadow existing labels.
3175    Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3176    Scope *S = CurScope;
3177    PushOnScopeChains(Res, S, true);
3178    return cast<LabelDecl>(Res);
3179  }
3180
3181  // Not a GNU local label.
3182  Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3183  // If we found a label, check to see if it is in the same context as us.
3184  // When in a Block, we don't want to reuse a label in an enclosing function.
3185  if (Res && Res->getDeclContext() != CurContext)
3186    Res = 0;
3187  if (Res == 0) {
3188    // If not forward referenced or defined already, create the backing decl.
3189    Res = LabelDecl::Create(Context, CurContext, Loc, II);
3190    Scope *S = CurScope->getFnParent();
3191    assert(S && "Not in a function?");
3192    PushOnScopeChains(Res, S, true);
3193  }
3194  return cast<LabelDecl>(Res);
3195}
3196
3197//===----------------------------------------------------------------------===//
3198// Typo correction
3199//===----------------------------------------------------------------------===//
3200
3201namespace {
3202
3203typedef SmallVector<TypoCorrection, 1> TypoResultList;
3204typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
3205typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
3206
3207static const unsigned MaxTypoDistanceResultSets = 5;
3208
3209class TypoCorrectionConsumer : public VisibleDeclConsumer {
3210  /// \brief The name written that is a typo in the source.
3211  StringRef Typo;
3212
3213  /// \brief The results found that have the smallest edit distance
3214  /// found (so far) with the typo name.
3215  ///
3216  /// The pointer value being set to the current DeclContext indicates
3217  /// whether there is a keyword with this name.
3218  TypoEditDistanceMap CorrectionResults;
3219
3220  Sema &SemaRef;
3221
3222public:
3223  explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
3224    : Typo(Typo->getName()),
3225      SemaRef(SemaRef) { }
3226
3227  virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3228                         bool InBaseClass);
3229  void FoundName(StringRef Name);
3230  void addKeywordResult(StringRef Keyword);
3231  void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
3232               NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
3233  void addCorrection(TypoCorrection Correction);
3234
3235  typedef TypoResultsMap::iterator result_iterator;
3236  typedef TypoEditDistanceMap::iterator distance_iterator;
3237  distance_iterator begin() { return CorrectionResults.begin(); }
3238  distance_iterator end()  { return CorrectionResults.end(); }
3239  void erase(distance_iterator I) { CorrectionResults.erase(I); }
3240  unsigned size() const { return CorrectionResults.size(); }
3241  bool empty() const { return CorrectionResults.empty(); }
3242
3243  TypoResultList &operator[](StringRef Name) {
3244    return CorrectionResults.begin()->second[Name];
3245  }
3246
3247  unsigned getBestEditDistance(bool Normalized) {
3248    if (CorrectionResults.empty())
3249      return (std::numeric_limits<unsigned>::max)();
3250
3251    unsigned BestED = CorrectionResults.begin()->first;
3252    return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
3253  }
3254
3255  TypoResultsMap &getBestResults() {
3256    return CorrectionResults.begin()->second;
3257  }
3258
3259};
3260
3261}
3262
3263void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
3264                                       DeclContext *Ctx, bool InBaseClass) {
3265  // Don't consider hidden names for typo correction.
3266  if (Hiding)
3267    return;
3268
3269  // Only consider entities with identifiers for names, ignoring
3270  // special names (constructors, overloaded operators, selectors,
3271  // etc.).
3272  IdentifierInfo *Name = ND->getIdentifier();
3273  if (!Name)
3274    return;
3275
3276  FoundName(Name->getName());
3277}
3278
3279void TypoCorrectionConsumer::FoundName(StringRef Name) {
3280  // Use a simple length-based heuristic to determine the minimum possible
3281  // edit distance. If the minimum isn't good enough, bail out early.
3282  unsigned MinED = abs((int)Name.size() - (int)Typo.size());
3283  if (MinED && Typo.size() / MinED < 3)
3284    return;
3285
3286  // Compute an upper bound on the allowable edit distance, so that the
3287  // edit-distance algorithm can short-circuit.
3288  unsigned UpperBound = (Typo.size() + 2) / 3;
3289
3290  // Compute the edit distance between the typo and the name of this
3291  // entity, and add the identifier to the list of results.
3292  addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
3293}
3294
3295void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3296  // Compute the edit distance between the typo and this keyword,
3297  // and add the keyword to the list of results.
3298  addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
3299}
3300
3301void TypoCorrectionConsumer::addName(StringRef Name,
3302                                     NamedDecl *ND,
3303                                     unsigned Distance,
3304                                     NestedNameSpecifier *NNS,
3305                                     bool isKeyword) {
3306  TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3307  if (isKeyword) TC.makeKeyword();
3308  addCorrection(TC);
3309}
3310
3311void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3312  StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3313  TypoResultList &CList =
3314      CorrectionResults[Correction.getEditDistance(false)][Name];
3315
3316  if (!CList.empty() && !CList.back().isResolved())
3317    CList.pop_back();
3318  if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3319    std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3320    for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3321         RI != RIEnd; ++RI) {
3322      // If the Correction refers to a decl already in the result list,
3323      // replace the existing result if the string representation of Correction
3324      // comes before the current result alphabetically, then stop as there is
3325      // nothing more to be done to add Correction to the candidate set.
3326      if (RI->getCorrectionDecl() == NewND) {
3327        if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3328          *RI = Correction;
3329        return;
3330      }
3331    }
3332  }
3333  if (CList.empty() || Correction.isResolved())
3334    CList.push_back(Correction);
3335
3336  while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3337    erase(llvm::prior(CorrectionResults.end()));
3338}
3339
3340// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3341// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3342// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3343static void getNestedNameSpecifierIdentifiers(
3344    NestedNameSpecifier *NNS,
3345    SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3346  if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3347    getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3348  else
3349    Identifiers.clear();
3350
3351  const IdentifierInfo *II = NULL;
3352
3353  switch (NNS->getKind()) {
3354  case NestedNameSpecifier::Identifier:
3355    II = NNS->getAsIdentifier();
3356    break;
3357
3358  case NestedNameSpecifier::Namespace:
3359    if (NNS->getAsNamespace()->isAnonymousNamespace())
3360      return;
3361    II = NNS->getAsNamespace()->getIdentifier();
3362    break;
3363
3364  case NestedNameSpecifier::NamespaceAlias:
3365    II = NNS->getAsNamespaceAlias()->getIdentifier();
3366    break;
3367
3368  case NestedNameSpecifier::TypeSpecWithTemplate:
3369  case NestedNameSpecifier::TypeSpec:
3370    II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3371    break;
3372
3373  case NestedNameSpecifier::Global:
3374    return;
3375  }
3376
3377  if (II)
3378    Identifiers.push_back(II);
3379}
3380
3381namespace {
3382
3383class SpecifierInfo {
3384 public:
3385  DeclContext* DeclCtx;
3386  NestedNameSpecifier* NameSpecifier;
3387  unsigned EditDistance;
3388
3389  SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3390      : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3391};
3392
3393typedef SmallVector<DeclContext*, 4> DeclContextList;
3394typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3395
3396class NamespaceSpecifierSet {
3397  ASTContext &Context;
3398  DeclContextList CurContextChain;
3399  SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3400  SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
3401  bool isSorted;
3402
3403  SpecifierInfoList Specifiers;
3404  llvm::SmallSetVector<unsigned, 4> Distances;
3405  llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3406
3407  /// \brief Helper for building the list of DeclContexts between the current
3408  /// context and the top of the translation unit
3409  static DeclContextList BuildContextChain(DeclContext *Start);
3410
3411  void SortNamespaces();
3412
3413 public:
3414  NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3415                        CXXScopeSpec *CurScopeSpec)
3416      : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3417        isSorted(false) {
3418    if (CurScopeSpec && CurScopeSpec->getScopeRep())
3419      getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3420                                        CurNameSpecifierIdentifiers);
3421    // Build the list of identifiers that would be used for an absolute
3422    // (from the global context) NestedNameSpecifier referring to the current
3423    // context.
3424    for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3425                                        CEnd = CurContextChain.rend();
3426         C != CEnd; ++C) {
3427      if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3428        CurContextIdentifiers.push_back(ND->getIdentifier());
3429    }
3430
3431    // Add the global context as a NestedNameSpecifier
3432    Distances.insert(1);
3433    DistanceMap[1].push_back(
3434        SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3435                      NestedNameSpecifier::GlobalSpecifier(Context), 1));
3436  }
3437
3438  /// \brief Add the namespace to the set, computing the corresponding
3439  /// NestedNameSpecifier and its distance in the process.
3440  void AddNamespace(NamespaceDecl *ND);
3441
3442  typedef SpecifierInfoList::iterator iterator;
3443  iterator begin() {
3444    if (!isSorted) SortNamespaces();
3445    return Specifiers.begin();
3446  }
3447  iterator end() { return Specifiers.end(); }
3448};
3449
3450}
3451
3452DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
3453  assert(Start && "Building a context chain from a null context");
3454  DeclContextList Chain;
3455  for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3456       DC = DC->getLookupParent()) {
3457    NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3458    if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3459        !(ND && ND->isAnonymousNamespace()))
3460      Chain.push_back(DC->getPrimaryContext());
3461  }
3462  return Chain;
3463}
3464
3465void NamespaceSpecifierSet::SortNamespaces() {
3466  SmallVector<unsigned, 4> sortedDistances;
3467  sortedDistances.append(Distances.begin(), Distances.end());
3468
3469  if (sortedDistances.size() > 1)
3470    std::sort(sortedDistances.begin(), sortedDistances.end());
3471
3472  Specifiers.clear();
3473  for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3474                                        DIEnd = sortedDistances.end();
3475       DI != DIEnd; ++DI) {
3476    SpecifierInfoList &SpecList = DistanceMap[*DI];
3477    Specifiers.append(SpecList.begin(), SpecList.end());
3478  }
3479
3480  isSorted = true;
3481}
3482
3483void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
3484  DeclContext *Ctx = cast<DeclContext>(ND);
3485  NestedNameSpecifier *NNS = NULL;
3486  unsigned NumSpecifiers = 0;
3487  DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3488  DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3489
3490  // Eliminate common elements from the two DeclContext chains.
3491  for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3492                                      CEnd = CurContextChain.rend();
3493       C != CEnd && !NamespaceDeclChain.empty() &&
3494       NamespaceDeclChain.back() == *C; ++C) {
3495    NamespaceDeclChain.pop_back();
3496  }
3497
3498  // Add an explicit leading '::' specifier if needed.
3499  if (NamespaceDeclChain.empty()) {
3500    NamespaceDeclChain = FullNamespaceDeclChain;
3501    NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3502  } else if (NamespaceDecl *ND =
3503                 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
3504    IdentifierInfo *Name = ND->getIdentifier();
3505    if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3506                  Name) != CurContextIdentifiers.end() ||
3507        std::find(CurNameSpecifierIdentifiers.begin(),
3508                  CurNameSpecifierIdentifiers.end(),
3509                  Name) != CurNameSpecifierIdentifiers.end()) {
3510      NamespaceDeclChain = FullNamespaceDeclChain;
3511      NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3512    }
3513  }
3514
3515  // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3516  for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3517                                      CEnd = NamespaceDeclChain.rend();
3518       C != CEnd; ++C) {
3519    NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3520    if (ND) {
3521      NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3522      ++NumSpecifiers;
3523    }
3524  }
3525
3526  // If the built NestedNameSpecifier would be replacing an existing
3527  // NestedNameSpecifier, use the number of component identifiers that
3528  // would need to be changed as the edit distance instead of the number
3529  // of components in the built NestedNameSpecifier.
3530  if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3531    SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3532    getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3533    NumSpecifiers = llvm::ComputeEditDistance(
3534      llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3535      llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3536  }
3537
3538  isSorted = false;
3539  Distances.insert(NumSpecifiers);
3540  DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3541}
3542
3543/// \brief Perform name lookup for a possible result for typo correction.
3544static void LookupPotentialTypoResult(Sema &SemaRef,
3545                                      LookupResult &Res,
3546                                      IdentifierInfo *Name,
3547                                      Scope *S, CXXScopeSpec *SS,
3548                                      DeclContext *MemberContext,
3549                                      bool EnteringContext,
3550                                      bool isObjCIvarLookup) {
3551  Res.suppressDiagnostics();
3552  Res.clear();
3553  Res.setLookupName(Name);
3554  if (MemberContext) {
3555    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3556      if (isObjCIvarLookup) {
3557        if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3558          Res.addDecl(Ivar);
3559          Res.resolveKind();
3560          return;
3561        }
3562      }
3563
3564      if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3565        Res.addDecl(Prop);
3566        Res.resolveKind();
3567        return;
3568      }
3569    }
3570
3571    SemaRef.LookupQualifiedName(Res, MemberContext);
3572    return;
3573  }
3574
3575  SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3576                           EnteringContext);
3577
3578  // Fake ivar lookup; this should really be part of
3579  // LookupParsedName.
3580  if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3581    if (Method->isInstanceMethod() && Method->getClassInterface() &&
3582        (Res.empty() ||
3583         (Res.isSingleResult() &&
3584          Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
3585       if (ObjCIvarDecl *IV
3586             = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3587         Res.addDecl(IV);
3588         Res.resolveKind();
3589       }
3590     }
3591  }
3592}
3593
3594/// \brief Add keywords to the consumer as possible typo corrections.
3595static void AddKeywordsToConsumer(Sema &SemaRef,
3596                                  TypoCorrectionConsumer &Consumer,
3597                                  Scope *S, CorrectionCandidateCallback &CCC,
3598                                  bool AfterNestedNameSpecifier) {
3599  if (AfterNestedNameSpecifier) {
3600    // For 'X::', we know exactly which keywords can appear next.
3601    Consumer.addKeywordResult("template");
3602    if (CCC.WantExpressionKeywords)
3603      Consumer.addKeywordResult("operator");
3604    return;
3605  }
3606
3607  if (CCC.WantObjCSuper)
3608    Consumer.addKeywordResult("super");
3609
3610  if (CCC.WantTypeSpecifiers) {
3611    // Add type-specifier keywords to the set of results.
3612    const char *CTypeSpecs[] = {
3613      "char", "const", "double", "enum", "float", "int", "long", "short",
3614      "signed", "struct", "union", "unsigned", "void", "volatile",
3615      "_Complex", "_Imaginary",
3616      // storage-specifiers as well
3617      "extern", "inline", "static", "typedef"
3618    };
3619
3620    const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3621    for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3622      Consumer.addKeywordResult(CTypeSpecs[I]);
3623
3624    if (SemaRef.getLangOpts().C99)
3625      Consumer.addKeywordResult("restrict");
3626    if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
3627      Consumer.addKeywordResult("bool");
3628    else if (SemaRef.getLangOpts().C99)
3629      Consumer.addKeywordResult("_Bool");
3630
3631    if (SemaRef.getLangOpts().CPlusPlus) {
3632      Consumer.addKeywordResult("class");
3633      Consumer.addKeywordResult("typename");
3634      Consumer.addKeywordResult("wchar_t");
3635
3636      if (SemaRef.getLangOpts().CPlusPlus11) {
3637        Consumer.addKeywordResult("char16_t");
3638        Consumer.addKeywordResult("char32_t");
3639        Consumer.addKeywordResult("constexpr");
3640        Consumer.addKeywordResult("decltype");
3641        Consumer.addKeywordResult("thread_local");
3642      }
3643    }
3644
3645    if (SemaRef.getLangOpts().GNUMode)
3646      Consumer.addKeywordResult("typeof");
3647  }
3648
3649  if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
3650    Consumer.addKeywordResult("const_cast");
3651    Consumer.addKeywordResult("dynamic_cast");
3652    Consumer.addKeywordResult("reinterpret_cast");
3653    Consumer.addKeywordResult("static_cast");
3654  }
3655
3656  if (CCC.WantExpressionKeywords) {
3657    Consumer.addKeywordResult("sizeof");
3658    if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
3659      Consumer.addKeywordResult("false");
3660      Consumer.addKeywordResult("true");
3661    }
3662
3663    if (SemaRef.getLangOpts().CPlusPlus) {
3664      const char *CXXExprs[] = {
3665        "delete", "new", "operator", "throw", "typeid"
3666      };
3667      const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3668      for (unsigned I = 0; I != NumCXXExprs; ++I)
3669        Consumer.addKeywordResult(CXXExprs[I]);
3670
3671      if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3672          cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3673        Consumer.addKeywordResult("this");
3674
3675      if (SemaRef.getLangOpts().CPlusPlus11) {
3676        Consumer.addKeywordResult("alignof");
3677        Consumer.addKeywordResult("nullptr");
3678      }
3679    }
3680
3681    if (SemaRef.getLangOpts().C11) {
3682      // FIXME: We should not suggest _Alignof if the alignof macro
3683      // is present.
3684      Consumer.addKeywordResult("_Alignof");
3685    }
3686  }
3687
3688  if (CCC.WantRemainingKeywords) {
3689    if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3690      // Statements.
3691      const char *CStmts[] = {
3692        "do", "else", "for", "goto", "if", "return", "switch", "while" };
3693      const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3694      for (unsigned I = 0; I != NumCStmts; ++I)
3695        Consumer.addKeywordResult(CStmts[I]);
3696
3697      if (SemaRef.getLangOpts().CPlusPlus) {
3698        Consumer.addKeywordResult("catch");
3699        Consumer.addKeywordResult("try");
3700      }
3701
3702      if (S && S->getBreakParent())
3703        Consumer.addKeywordResult("break");
3704
3705      if (S && S->getContinueParent())
3706        Consumer.addKeywordResult("continue");
3707
3708      if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3709        Consumer.addKeywordResult("case");
3710        Consumer.addKeywordResult("default");
3711      }
3712    } else {
3713      if (SemaRef.getLangOpts().CPlusPlus) {
3714        Consumer.addKeywordResult("namespace");
3715        Consumer.addKeywordResult("template");
3716      }
3717
3718      if (S && S->isClassScope()) {
3719        Consumer.addKeywordResult("explicit");
3720        Consumer.addKeywordResult("friend");
3721        Consumer.addKeywordResult("mutable");
3722        Consumer.addKeywordResult("private");
3723        Consumer.addKeywordResult("protected");
3724        Consumer.addKeywordResult("public");
3725        Consumer.addKeywordResult("virtual");
3726      }
3727    }
3728
3729    if (SemaRef.getLangOpts().CPlusPlus) {
3730      Consumer.addKeywordResult("using");
3731
3732      if (SemaRef.getLangOpts().CPlusPlus11)
3733        Consumer.addKeywordResult("static_assert");
3734    }
3735  }
3736}
3737
3738static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3739                              TypoCorrection &Candidate) {
3740  Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3741  return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3742}
3743
3744/// \brief Try to "correct" a typo in the source code by finding
3745/// visible declarations whose names are similar to the name that was
3746/// present in the source code.
3747///
3748/// \param TypoName the \c DeclarationNameInfo structure that contains
3749/// the name that was present in the source code along with its location.
3750///
3751/// \param LookupKind the name-lookup criteria used to search for the name.
3752///
3753/// \param S the scope in which name lookup occurs.
3754///
3755/// \param SS the nested-name-specifier that precedes the name we're
3756/// looking for, if present.
3757///
3758/// \param CCC A CorrectionCandidateCallback object that provides further
3759/// validation of typo correction candidates. It also provides flags for
3760/// determining the set of keywords permitted.
3761///
3762/// \param MemberContext if non-NULL, the context in which to look for
3763/// a member access expression.
3764///
3765/// \param EnteringContext whether we're entering the context described by
3766/// the nested-name-specifier SS.
3767///
3768/// \param OPT when non-NULL, the search for visible declarations will
3769/// also walk the protocols in the qualified interfaces of \p OPT.
3770///
3771/// \returns a \c TypoCorrection containing the corrected name if the typo
3772/// along with information such as the \c NamedDecl where the corrected name
3773/// was declared, and any additional \c NestedNameSpecifier needed to access
3774/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3775TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3776                                 Sema::LookupNameKind LookupKind,
3777                                 Scope *S, CXXScopeSpec *SS,
3778                                 CorrectionCandidateCallback &CCC,
3779                                 DeclContext *MemberContext,
3780                                 bool EnteringContext,
3781                                 const ObjCObjectPointerType *OPT) {
3782  if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
3783    return TypoCorrection();
3784
3785  // In Microsoft mode, don't perform typo correction in a template member
3786  // function dependent context because it interferes with the "lookup into
3787  // dependent bases of class templates" feature.
3788  if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
3789      isa<CXXMethodDecl>(CurContext))
3790    return TypoCorrection();
3791
3792  // We only attempt to correct typos for identifiers.
3793  IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
3794  if (!Typo)
3795    return TypoCorrection();
3796
3797  // If the scope specifier itself was invalid, don't try to correct
3798  // typos.
3799  if (SS && SS->isInvalid())
3800    return TypoCorrection();
3801
3802  // Never try to correct typos during template deduction or
3803  // instantiation.
3804  if (!ActiveTemplateInstantiations.empty())
3805    return TypoCorrection();
3806
3807  // Don't try to correct 'super'.
3808  if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3809    return TypoCorrection();
3810
3811  NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
3812
3813  TypoCorrectionConsumer Consumer(*this, Typo);
3814
3815  // If a callback object considers an empty typo correction candidate to be
3816  // viable, assume it does not do any actual validation of the candidates.
3817  TypoCorrection EmptyCorrection;
3818  bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
3819
3820  // Perform name lookup to find visible, similarly-named entities.
3821  bool IsUnqualifiedLookup = false;
3822  DeclContext *QualifiedDC = MemberContext;
3823  if (MemberContext) {
3824    LookupVisibleDecls(MemberContext, LookupKind, Consumer);
3825
3826    // Look in qualified interfaces.
3827    if (OPT) {
3828      for (ObjCObjectPointerType::qual_iterator
3829             I = OPT->qual_begin(), E = OPT->qual_end();
3830           I != E; ++I)
3831        LookupVisibleDecls(*I, LookupKind, Consumer);
3832    }
3833  } else if (SS && SS->isSet()) {
3834    QualifiedDC = computeDeclContext(*SS, EnteringContext);
3835    if (!QualifiedDC)
3836      return TypoCorrection();
3837
3838    // Provide a stop gap for files that are just seriously broken.  Trying
3839    // to correct all typos can turn into a HUGE performance penalty, causing
3840    // some files to take minutes to get rejected by the parser.
3841    if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3842      return TypoCorrection();
3843    ++TyposCorrected;
3844
3845    LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
3846  } else {
3847    IsUnqualifiedLookup = true;
3848    UnqualifiedTyposCorrectedMap::iterator Cached
3849      = UnqualifiedTyposCorrected.find(Typo);
3850    if (Cached != UnqualifiedTyposCorrected.end()) {
3851      // Add the cached value, unless it's a keyword or fails validation. In the
3852      // keyword case, we'll end up adding the keyword below.
3853      if (Cached->second) {
3854        if (!Cached->second.isKeyword() &&
3855            isCandidateViable(CCC, Cached->second))
3856          Consumer.addCorrection(Cached->second);
3857      } else {
3858        // Only honor no-correction cache hits when a callback that will validate
3859        // correction candidates is not being used.
3860        if (!ValidatingCallback)
3861          return TypoCorrection();
3862      }
3863    }
3864    if (Cached == UnqualifiedTyposCorrected.end()) {
3865      // Provide a stop gap for files that are just seriously broken.  Trying
3866      // to correct all typos can turn into a HUGE performance penalty, causing
3867      // some files to take minutes to get rejected by the parser.
3868      if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3869        return TypoCorrection();
3870    }
3871  }
3872
3873  // Determine whether we are going to search in the various namespaces for
3874  // corrections.
3875  bool SearchNamespaces
3876    = getLangOpts().CPlusPlus &&
3877      (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
3878  // In a few cases we *only* want to search for corrections bases on just
3879  // adding or changing the nested name specifier.
3880  bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
3881
3882  if (IsUnqualifiedLookup || SearchNamespaces) {
3883    // For unqualified lookup, look through all of the names that we have
3884    // seen in this translation unit.
3885    // FIXME: Re-add the ability to skip very unlikely potential corrections.
3886    for (IdentifierTable::iterator I = Context.Idents.begin(),
3887                                IEnd = Context.Idents.end();
3888         I != IEnd; ++I)
3889      Consumer.FoundName(I->getKey());
3890
3891    // Walk through identifiers in external identifier sources.
3892    // FIXME: Re-add the ability to skip very unlikely potential corrections.
3893    if (IdentifierInfoLookup *External
3894                            = Context.Idents.getExternalIdentifierLookup()) {
3895      OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
3896      do {
3897        StringRef Name = Iter->Next();
3898        if (Name.empty())
3899          break;
3900
3901        Consumer.FoundName(Name);
3902      } while (true);
3903    }
3904  }
3905
3906  AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
3907
3908  // If we haven't found anything, we're done.
3909  if (Consumer.empty()) {
3910    // If this was an unqualified lookup, note that no correction was found.
3911    if (IsUnqualifiedLookup)
3912      (void)UnqualifiedTyposCorrected[Typo];
3913
3914    return TypoCorrection();
3915  }
3916
3917  // Make sure the best edit distance (prior to adding any namespace qualifiers)
3918  // is not more that about a third of the length of the typo's identifier.
3919  unsigned ED = Consumer.getBestEditDistance(true);
3920  if (ED > 0 && Typo->getName().size() / ED < 3) {
3921    // If this was an unqualified lookup, note that no correction was found.
3922    if (IsUnqualifiedLookup)
3923      (void)UnqualifiedTyposCorrected[Typo];
3924
3925    return TypoCorrection();
3926  }
3927
3928  // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3929  // to search those namespaces.
3930  if (SearchNamespaces) {
3931    // Load any externally-known namespaces.
3932    if (ExternalSource && !LoadedExternalKnownNamespaces) {
3933      SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
3934      LoadedExternalKnownNamespaces = true;
3935      ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3936      for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3937        KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3938    }
3939
3940    for (llvm::MapVector<NamespaceDecl*, bool>::iterator
3941           KNI = KnownNamespaces.begin(),
3942           KNIEnd = KnownNamespaces.end();
3943         KNI != KNIEnd; ++KNI)
3944      Namespaces.AddNamespace(KNI->first);
3945  }
3946
3947  // Weed out any names that could not be found by name lookup or, if a
3948  // CorrectionCandidateCallback object was provided, failed validation.
3949  SmallVector<TypoCorrection, 16> QualifiedResults;
3950  LookupResult TmpRes(*this, TypoName, LookupKind);
3951  TmpRes.suppressDiagnostics();
3952  while (!Consumer.empty()) {
3953    TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3954    unsigned ED = DI->first;
3955    for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3956                                              IEnd = DI->second.end();
3957         I != IEnd; /* Increment in loop. */) {
3958      // If we only want nested name specifier corrections, ignore potential
3959      // corrections that have a different base identifier from the typo.
3960      if (AllowOnlyNNSChanges &&
3961          I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3962        TypoCorrectionConsumer::result_iterator Prev = I;
3963        ++I;
3964        DI->second.erase(Prev);
3965        continue;
3966      }
3967
3968      // If the item already has been looked up or is a keyword, keep it.
3969      // If a validator callback object was given, drop the correction
3970      // unless it passes validation.
3971      bool Viable = false;
3972      for (TypoResultList::iterator RI = I->second.begin();
3973           RI != I->second.end(); /* Increment in loop. */) {
3974        TypoResultList::iterator Prev = RI;
3975        ++RI;
3976        if (Prev->isResolved()) {
3977          if (!isCandidateViable(CCC, *Prev))
3978            RI = I->second.erase(Prev);
3979          else
3980            Viable = true;
3981        }
3982      }
3983      if (Viable || I->second.empty()) {
3984        TypoCorrectionConsumer::result_iterator Prev = I;
3985        ++I;
3986        if (!Viable)
3987          DI->second.erase(Prev);
3988        continue;
3989      }
3990      assert(I->second.size() == 1 && "Expected a single unresolved candidate");
3991
3992      // Perform name lookup on this name.
3993      TypoCorrection &Candidate = I->second.front();
3994      IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3995      DeclContext *TempMemberContext = MemberContext;
3996      CXXScopeSpec *TempSS = SS;
3997retry_lookup:
3998      LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
3999                                TempMemberContext, EnteringContext,
4000                                CCC.IsObjCIvarLookup);
4001
4002      switch (TmpRes.getResultKind()) {
4003      case LookupResult::NotFound:
4004      case LookupResult::NotFoundInCurrentInstantiation:
4005      case LookupResult::FoundUnresolvedValue:
4006        if (TempSS) {
4007          // Immediately retry the lookup without the given CXXScopeSpec
4008          TempSS = NULL;
4009          Candidate.WillReplaceSpecifier(true);
4010          goto retry_lookup;
4011        }
4012        if (TempMemberContext) {
4013          if (SS && !TempSS)
4014            TempSS = SS;
4015          TempMemberContext = NULL;
4016          goto retry_lookup;
4017        }
4018        QualifiedResults.push_back(Candidate);
4019        // We didn't find this name in our scope, or didn't like what we found;
4020        // ignore it.
4021        {
4022          TypoCorrectionConsumer::result_iterator Next = I;
4023          ++Next;
4024          DI->second.erase(I);
4025          I = Next;
4026        }
4027        break;
4028
4029      case LookupResult::Ambiguous:
4030        // We don't deal with ambiguities.
4031        return TypoCorrection();
4032
4033      case LookupResult::FoundOverloaded: {
4034        TypoCorrectionConsumer::result_iterator Prev = I;
4035        // Store all of the Decls for overloaded symbols
4036        for (LookupResult::iterator TRD = TmpRes.begin(),
4037                                 TRDEnd = TmpRes.end();
4038             TRD != TRDEnd; ++TRD)
4039          Candidate.addCorrectionDecl(*TRD);
4040        ++I;
4041        if (!isCandidateViable(CCC, Candidate)) {
4042          QualifiedResults.push_back(Candidate);
4043          DI->second.erase(Prev);
4044        }
4045        break;
4046      }
4047
4048      case LookupResult::Found: {
4049        TypoCorrectionConsumer::result_iterator Prev = I;
4050        Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
4051        ++I;
4052        if (!isCandidateViable(CCC, Candidate)) {
4053          QualifiedResults.push_back(Candidate);
4054          DI->second.erase(Prev);
4055        }
4056        break;
4057      }
4058
4059      }
4060    }
4061
4062    if (DI->second.empty())
4063      Consumer.erase(DI);
4064    else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
4065      // If there are results in the closest possible bucket, stop
4066      break;
4067
4068    // Only perform the qualified lookups for C++
4069    if (SearchNamespaces) {
4070      TmpRes.suppressDiagnostics();
4071      for (SmallVector<TypoCorrection,
4072                       16>::iterator QRI = QualifiedResults.begin(),
4073                                  QRIEnd = QualifiedResults.end();
4074           QRI != QRIEnd; ++QRI) {
4075        for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4076                                          NIEnd = Namespaces.end();
4077             NI != NIEnd; ++NI) {
4078          DeclContext *Ctx = NI->DeclCtx;
4079
4080          // FIXME: Stop searching once the namespaces are too far away to create
4081          // acceptable corrections for this identifier (since the namespaces
4082          // are sorted in ascending order by edit distance).
4083
4084          TmpRes.clear();
4085          TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
4086          if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4087
4088          // Any corrections added below will be validated in subsequent
4089          // iterations of the main while() loop over the Consumer's contents.
4090          switch (TmpRes.getResultKind()) {
4091          case LookupResult::Found:
4092          case LookupResult::FoundOverloaded: {
4093            TypoCorrection TC(*QRI);
4094            TC.setCorrectionSpecifier(NI->NameSpecifier);
4095            TC.setQualifierDistance(NI->EditDistance);
4096            TC.setCallbackDistance(0); // Reset the callback distance
4097            for (LookupResult::iterator TRD = TmpRes.begin(),
4098                                     TRDEnd = TmpRes.end();
4099                 TRD != TRDEnd; ++TRD)
4100              TC.addCorrectionDecl(*TRD);
4101            Consumer.addCorrection(TC);
4102            break;
4103          }
4104          case LookupResult::NotFound:
4105          case LookupResult::NotFoundInCurrentInstantiation:
4106          case LookupResult::Ambiguous:
4107          case LookupResult::FoundUnresolvedValue:
4108            break;
4109          }
4110        }
4111      }
4112    }
4113
4114    QualifiedResults.clear();
4115  }
4116
4117  // No corrections remain...
4118  if (Consumer.empty()) return TypoCorrection();
4119
4120  TypoResultsMap &BestResults = Consumer.getBestResults();
4121  ED = Consumer.getBestEditDistance(true);
4122
4123  if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
4124    // If this was an unqualified lookup and we believe the callback
4125    // object wouldn't have filtered out possible corrections, note
4126    // that no correction was found.
4127    if (IsUnqualifiedLookup && !ValidatingCallback)
4128      (void)UnqualifiedTyposCorrected[Typo];
4129
4130    return TypoCorrection();
4131  }
4132
4133  // If only a single name remains, return that result.
4134  if (BestResults.size() == 1) {
4135    const TypoResultList &CorrectionList = BestResults.begin()->second;
4136    const TypoCorrection &Result = CorrectionList.front();
4137    if (CorrectionList.size() != 1) return TypoCorrection();
4138
4139    // Don't correct to a keyword that's the same as the typo; the keyword
4140    // wasn't actually in scope.
4141    if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4142
4143    // Record the correction for unqualified lookup.
4144    if (IsUnqualifiedLookup)
4145      UnqualifiedTyposCorrected[Typo] = Result;
4146
4147    TypoCorrection TC = Result;
4148    TC.setCorrectionRange(SS, TypoName);
4149    return TC;
4150  }
4151  else if (BestResults.size() > 1
4152           // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4153           // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4154           // some instances of CTC_Unknown, while WantRemainingKeywords is true
4155           // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4156           && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
4157           && BestResults["super"].front().isKeyword()) {
4158    // Prefer 'super' when we're completing in a message-receiver
4159    // context.
4160
4161    // Don't correct to a keyword that's the same as the typo; the keyword
4162    // wasn't actually in scope.
4163    if (ED == 0) return TypoCorrection();
4164
4165    // Record the correction for unqualified lookup.
4166    if (IsUnqualifiedLookup)
4167      UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
4168
4169    TypoCorrection TC = BestResults["super"].front();
4170    TC.setCorrectionRange(SS, TypoName);
4171    return TC;
4172  }
4173
4174  // If this was an unqualified lookup and we believe the callback object did
4175  // not filter out possible corrections, note that no correction was found.
4176  if (IsUnqualifiedLookup && !ValidatingCallback)
4177    (void)UnqualifiedTyposCorrected[Typo];
4178
4179  return TypoCorrection();
4180}
4181
4182void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4183  if (!CDecl) return;
4184
4185  if (isKeyword())
4186    CorrectionDecls.clear();
4187
4188  CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
4189
4190  if (!CorrectionName)
4191    CorrectionName = CDecl->getDeclName();
4192}
4193
4194std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4195  if (CorrectionNameSpec) {
4196    std::string tmpBuffer;
4197    llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4198    CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4199    PrefixOStream << CorrectionName;
4200    return PrefixOStream.str();
4201  }
4202
4203  return CorrectionName.getAsString();
4204}
4205
4206bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4207  if (!candidate.isResolved())
4208    return true;
4209
4210  if (candidate.isKeyword())
4211    return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4212           WantRemainingKeywords || WantObjCSuper;
4213
4214  for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4215                                           CDeclEnd = candidate.end();
4216       CDecl != CDeclEnd; ++CDecl) {
4217    if (!isa<TypeDecl>(*CDecl))
4218      return true;
4219  }
4220
4221  return WantTypeSpecifiers;
4222}
4223