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