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