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