SemaLookup.cpp revision 226633
1193326Sed//===--------------------- SemaLookup.cpp - Name Lookup  ------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements name lookup for C, C++, Objective-C, and
11193326Sed//  Objective-C++.
12193326Sed//
13193326Sed//===----------------------------------------------------------------------===//
14212904Sdim#include "clang/Sema/Sema.h"
15212904Sdim#include "clang/Sema/SemaInternal.h"
16212904Sdim#include "clang/Sema/Lookup.h"
17223017Sdim#include "clang/Sema/Overload.h"
18212904Sdim#include "clang/Sema/DeclSpec.h"
19212904Sdim#include "clang/Sema/Scope.h"
20212904Sdim#include "clang/Sema/ScopeInfo.h"
21212904Sdim#include "clang/Sema/TemplateDeduction.h"
22219077Sdim#include "clang/Sema/ExternalSemaSource.h"
23224145Sdim#include "clang/Sema/TypoCorrection.h"
24193326Sed#include "clang/AST/ASTContext.h"
25198092Srdivacky#include "clang/AST/CXXInheritance.h"
26193326Sed#include "clang/AST/Decl.h"
27193326Sed#include "clang/AST/DeclCXX.h"
28193326Sed#include "clang/AST/DeclObjC.h"
29193326Sed#include "clang/AST/DeclTemplate.h"
30193326Sed#include "clang/AST/Expr.h"
31198092Srdivacky#include "clang/AST/ExprCXX.h"
32194179Sed#include "clang/Basic/Builtins.h"
33193326Sed#include "clang/Basic/LangOptions.h"
34212904Sdim#include "llvm/ADT/DenseSet.h"
35193326Sed#include "llvm/ADT/STLExtras.h"
36193326Sed#include "llvm/ADT/SmallPtrSet.h"
37218893Sdim#include "llvm/ADT/StringMap.h"
38226633Sdim#include "llvm/ADT/TinyPtrVector.h"
39198092Srdivacky#include "llvm/Support/ErrorHandling.h"
40218893Sdim#include <limits>
41201361Srdivacky#include <list>
42193326Sed#include <set>
43193326Sed#include <vector>
44193326Sed#include <iterator>
45193326Sed#include <utility>
46193326Sed#include <algorithm>
47224145Sdim#include <map>
48193326Sed
49193326Sedusing namespace clang;
50212904Sdimusing namespace sema;
51193326Sed
52199482Srdivackynamespace {
53199482Srdivacky  class UnqualUsingEntry {
54199482Srdivacky    const DeclContext *Nominated;
55199482Srdivacky    const DeclContext *CommonAncestor;
56193326Sed
57199482Srdivacky  public:
58199482Srdivacky    UnqualUsingEntry(const DeclContext *Nominated,
59199482Srdivacky                     const DeclContext *CommonAncestor)
60199482Srdivacky      : Nominated(Nominated), CommonAncestor(CommonAncestor) {
61199482Srdivacky    }
62193326Sed
63199482Srdivacky    const DeclContext *getCommonAncestor() const {
64199482Srdivacky      return CommonAncestor;
65199482Srdivacky    }
66193326Sed
67199482Srdivacky    const DeclContext *getNominatedNamespace() const {
68199482Srdivacky      return Nominated;
69199482Srdivacky    }
70193326Sed
71199482Srdivacky    // Sort by the pointer value of the common ancestor.
72199482Srdivacky    struct Comparator {
73199482Srdivacky      bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
74199482Srdivacky        return L.getCommonAncestor() < R.getCommonAncestor();
75199482Srdivacky      }
76193326Sed
77199482Srdivacky      bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
78199482Srdivacky        return E.getCommonAncestor() < DC;
79199482Srdivacky      }
80193326Sed
81199482Srdivacky      bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
82199482Srdivacky        return DC < E.getCommonAncestor();
83199482Srdivacky      }
84199482Srdivacky    };
85199482Srdivacky  };
86193326Sed
87199482Srdivacky  /// A collection of using directives, as used by C++ unqualified
88199482Srdivacky  /// lookup.
89199482Srdivacky  class UnqualUsingDirectiveSet {
90226633Sdim    typedef SmallVector<UnqualUsingEntry, 8> ListTy;
91193326Sed
92199482Srdivacky    ListTy list;
93199482Srdivacky    llvm::SmallPtrSet<DeclContext*, 8> visited;
94193326Sed
95199482Srdivacky  public:
96199482Srdivacky    UnqualUsingDirectiveSet() {}
97193326Sed
98199482Srdivacky    void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
99218893Sdim      // C++ [namespace.udir]p1:
100199482Srdivacky      //   During unqualified name lookup, the names appear as if they
101199482Srdivacky      //   were declared in the nearest enclosing namespace which contains
102199482Srdivacky      //   both the using-directive and the nominated namespace.
103199482Srdivacky      DeclContext *InnermostFileDC
104199482Srdivacky        = static_cast<DeclContext*>(InnermostFileScope->getEntity());
105199482Srdivacky      assert(InnermostFileDC && InnermostFileDC->isFileContext());
106193326Sed
107199482Srdivacky      for (; S; S = S->getParent()) {
108199482Srdivacky        if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
109199482Srdivacky          DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
110199482Srdivacky          visit(Ctx, EffectiveDC);
111199482Srdivacky        } else {
112199482Srdivacky          Scope::udir_iterator I = S->using_directives_begin(),
113199482Srdivacky                             End = S->using_directives_end();
114218893Sdim
115199482Srdivacky          for (; I != End; ++I)
116212904Sdim            visit(*I, InnermostFileDC);
117199482Srdivacky        }
118199482Srdivacky      }
119199482Srdivacky    }
120193326Sed
121199482Srdivacky    // Visits a context and collect all of its using directives
122199482Srdivacky    // recursively.  Treats all using directives as if they were
123199482Srdivacky    // declared in the context.
124199482Srdivacky    //
125199482Srdivacky    // A given context is only every visited once, so it is important
126199482Srdivacky    // that contexts be visited from the inside out in order to get
127199482Srdivacky    // the effective DCs right.
128199482Srdivacky    void visit(DeclContext *DC, DeclContext *EffectiveDC) {
129199482Srdivacky      if (!visited.insert(DC))
130199482Srdivacky        return;
131193326Sed
132199482Srdivacky      addUsingDirectives(DC, EffectiveDC);
133199482Srdivacky    }
134199482Srdivacky
135199482Srdivacky    // Visits a using directive and collects all of its using
136199482Srdivacky    // directives recursively.  Treats all using directives as if they
137199482Srdivacky    // were declared in the effective DC.
138199482Srdivacky    void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
139199482Srdivacky      DeclContext *NS = UD->getNominatedNamespace();
140199482Srdivacky      if (!visited.insert(NS))
141199482Srdivacky        return;
142199482Srdivacky
143199482Srdivacky      addUsingDirective(UD, EffectiveDC);
144199482Srdivacky      addUsingDirectives(NS, EffectiveDC);
145199482Srdivacky    }
146199482Srdivacky
147199482Srdivacky    // Adds all the using directives in a context (and those nominated
148199482Srdivacky    // by its using directives, transitively) as if they appeared in
149199482Srdivacky    // the given effective context.
150199482Srdivacky    void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
151226633Sdim      SmallVector<DeclContext*,4> queue;
152199482Srdivacky      while (true) {
153199482Srdivacky        DeclContext::udir_iterator I, End;
154199482Srdivacky        for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
155199482Srdivacky          UsingDirectiveDecl *UD = *I;
156199482Srdivacky          DeclContext *NS = UD->getNominatedNamespace();
157199482Srdivacky          if (visited.insert(NS)) {
158199482Srdivacky            addUsingDirective(UD, EffectiveDC);
159199482Srdivacky            queue.push_back(NS);
160199482Srdivacky          }
161199482Srdivacky        }
162199482Srdivacky
163199482Srdivacky        if (queue.empty())
164199482Srdivacky          return;
165199482Srdivacky
166199482Srdivacky        DC = queue.back();
167199482Srdivacky        queue.pop_back();
168193326Sed      }
169193326Sed    }
170199482Srdivacky
171199482Srdivacky    // Add a using directive as if it had been declared in the given
172199482Srdivacky    // context.  This helps implement C++ [namespace.udir]p3:
173199482Srdivacky    //   The using-directive is transitive: if a scope contains a
174199482Srdivacky    //   using-directive that nominates a second namespace that itself
175199482Srdivacky    //   contains using-directives, the effect is as if the
176199482Srdivacky    //   using-directives from the second namespace also appeared in
177199482Srdivacky    //   the first.
178199482Srdivacky    void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
179199482Srdivacky      // Find the common ancestor between the effective context and
180199482Srdivacky      // the nominated namespace.
181199482Srdivacky      DeclContext *Common = UD->getNominatedNamespace();
182199482Srdivacky      while (!Common->Encloses(EffectiveDC))
183199482Srdivacky        Common = Common->getParent();
184199482Srdivacky      Common = Common->getPrimaryContext();
185218893Sdim
186199482Srdivacky      list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
187199482Srdivacky    }
188199482Srdivacky
189199482Srdivacky    void done() {
190199482Srdivacky      std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
191199482Srdivacky    }
192199482Srdivacky
193199482Srdivacky    typedef ListTy::const_iterator const_iterator;
194218893Sdim
195199482Srdivacky    const_iterator begin() const { return list.begin(); }
196199482Srdivacky    const_iterator end() const { return list.end(); }
197199482Srdivacky
198199482Srdivacky    std::pair<const_iterator,const_iterator>
199199482Srdivacky    getNamespacesFor(DeclContext *DC) const {
200199482Srdivacky      return std::equal_range(begin(), end(), DC->getPrimaryContext(),
201199482Srdivacky                              UnqualUsingEntry::Comparator());
202199482Srdivacky    }
203199482Srdivacky  };
204193326Sed}
205193326Sed
206193326Sed// Retrieve the set of identifier namespaces that correspond to a
207193326Sed// specific kind of name lookup.
208201361Srdivackystatic inline unsigned getIDNS(Sema::LookupNameKind NameKind,
209201361Srdivacky                               bool CPlusPlus,
210201361Srdivacky                               bool Redeclaration) {
211193326Sed  unsigned IDNS = 0;
212193326Sed  switch (NameKind) {
213224145Sdim  case Sema::LookupObjCImplicitSelfParam:
214193326Sed  case Sema::LookupOrdinaryName:
215193326Sed  case Sema::LookupRedeclarationWithLinkage:
216193326Sed    IDNS = Decl::IDNS_Ordinary;
217201361Srdivacky    if (CPlusPlus) {
218207619Srdivacky      IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
219218893Sdim      if (Redeclaration)
220218893Sdim        IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
221201361Srdivacky    }
222193326Sed    break;
223193326Sed
224207619Srdivacky  case Sema::LookupOperatorName:
225207619Srdivacky    // Operator lookup is its own crazy thing;  it is not the same
226207619Srdivacky    // as (e.g.) looking up an operator name for redeclaration.
227207619Srdivacky    assert(!Redeclaration && "cannot do redeclaration operator lookup");
228207619Srdivacky    IDNS = Decl::IDNS_NonMemberOperator;
229207619Srdivacky    break;
230207619Srdivacky
231193326Sed  case Sema::LookupTagName:
232207619Srdivacky    if (CPlusPlus) {
233207619Srdivacky      IDNS = Decl::IDNS_Type;
234207619Srdivacky
235207619Srdivacky      // When looking for a redeclaration of a tag name, we add:
236207619Srdivacky      // 1) TagFriend to find undeclared friend decls
237207619Srdivacky      // 2) Namespace because they can't "overload" with tag decls.
238207619Srdivacky      // 3) Tag because it includes class templates, which can't
239207619Srdivacky      //    "overload" with tag decls.
240207619Srdivacky      if (Redeclaration)
241207619Srdivacky        IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
242207619Srdivacky    } else {
243207619Srdivacky      IDNS = Decl::IDNS_Tag;
244207619Srdivacky    }
245193326Sed    break;
246218893Sdim  case Sema::LookupLabel:
247218893Sdim    IDNS = Decl::IDNS_Label;
248218893Sdim    break;
249218893Sdim
250193326Sed  case Sema::LookupMemberName:
251193326Sed    IDNS = Decl::IDNS_Member;
252193326Sed    if (CPlusPlus)
253198092Srdivacky      IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
254193326Sed    break;
255193326Sed
256193326Sed  case Sema::LookupNestedNameSpecifierName:
257207619Srdivacky    IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
258207619Srdivacky    break;
259207619Srdivacky
260193326Sed  case Sema::LookupNamespaceName:
261207619Srdivacky    IDNS = Decl::IDNS_Namespace;
262193326Sed    break;
263193326Sed
264200583Srdivacky  case Sema::LookupUsingDeclName:
265200583Srdivacky    IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
266200583Srdivacky         | Decl::IDNS_Member | Decl::IDNS_Using;
267200583Srdivacky    break;
268200583Srdivacky
269193326Sed  case Sema::LookupObjCProtocolName:
270193326Sed    IDNS = Decl::IDNS_ObjCProtocol;
271193326Sed    break;
272218893Sdim
273212904Sdim  case Sema::LookupAnyName:
274218893Sdim    IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
275212904Sdim      | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
276212904Sdim      | Decl::IDNS_Type;
277212904Sdim    break;
278193326Sed  }
279193326Sed  return IDNS;
280193326Sed}
281193326Sed
282201361Srdivackyvoid LookupResult::configure() {
283218893Sdim  IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
284201361Srdivacky                 isForRedeclaration());
285206084Srdivacky
286206084Srdivacky  // If we're looking for one of the allocation or deallocation
287206084Srdivacky  // operators, make sure that the implicitly-declared new and delete
288206084Srdivacky  // operators can be found.
289206084Srdivacky  if (!isForRedeclaration()) {
290212904Sdim    switch (NameInfo.getName().getCXXOverloadedOperator()) {
291206084Srdivacky    case OO_New:
292206084Srdivacky    case OO_Delete:
293206084Srdivacky    case OO_Array_New:
294206084Srdivacky    case OO_Array_Delete:
295206084Srdivacky      SemaRef.DeclareGlobalNewDelete();
296206084Srdivacky      break;
297206084Srdivacky
298206084Srdivacky    default:
299206084Srdivacky      break;
300206084Srdivacky    }
301206084Srdivacky  }
302201361Srdivacky}
303201361Srdivacky
304212904Sdimvoid LookupResult::sanity() const {
305212904Sdim  assert(ResultKind != NotFound || Decls.size() == 0);
306212904Sdim  assert(ResultKind != Found || Decls.size() == 1);
307212904Sdim  assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
308212904Sdim         (Decls.size() == 1 &&
309212904Sdim          isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
310212904Sdim  assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
311212904Sdim  assert(ResultKind != Ambiguous || Decls.size() > 1 ||
312218893Sdim         (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
313218893Sdim                                Ambiguity == AmbiguousBaseSubobjectTypes)));
314212904Sdim  assert((Paths != NULL) == (ResultKind == Ambiguous &&
315212904Sdim                             (Ambiguity == AmbiguousBaseSubobjectTypes ||
316212904Sdim                              Ambiguity == AmbiguousBaseSubobjects)));
317212904Sdim}
318212904Sdim
319198092Srdivacky// Necessary because CXXBasePaths is not complete in Sema.h
320199482Srdivackyvoid LookupResult::deletePaths(CXXBasePaths *Paths) {
321198092Srdivacky  delete Paths;
322193326Sed}
323193326Sed
324199990Srdivacky/// Resolves the result kind of this lookup.
325199482Srdivackyvoid LookupResult::resolveKind() {
326198092Srdivacky  unsigned N = Decls.size();
327218893Sdim
328198092Srdivacky  // Fast case: no possible ambiguity.
329199512Srdivacky  if (N == 0) {
330202879Srdivacky    assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
331199512Srdivacky    return;
332199512Srdivacky  }
333199512Srdivacky
334199990Srdivacky  // If there's a single decl, we need to examine it to decide what
335199990Srdivacky  // kind of lookup this is.
336199482Srdivacky  if (N == 1) {
337207619Srdivacky    NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
338207619Srdivacky    if (isa<FunctionTemplateDecl>(D))
339199990Srdivacky      ResultKind = FoundOverloaded;
340207619Srdivacky    else if (isa<UnresolvedUsingValueDecl>(D))
341199482Srdivacky      ResultKind = FoundUnresolvedValue;
342199482Srdivacky    return;
343199482Srdivacky  }
344193326Sed
345198092Srdivacky  // Don't do any extra resolution if we've already resolved as ambiguous.
346199482Srdivacky  if (ResultKind == Ambiguous) return;
347195099Sed
348198092Srdivacky  llvm::SmallPtrSet<NamedDecl*, 16> Unique;
349212904Sdim  llvm::SmallPtrSet<QualType, 16> UniqueTypes;
350218893Sdim
351198092Srdivacky  bool Ambiguous = false;
352198092Srdivacky  bool HasTag = false, HasFunction = false, HasNonFunction = false;
353199990Srdivacky  bool HasFunctionTemplate = false, HasUnresolved = false;
354193326Sed
355198092Srdivacky  unsigned UniqueTagIndex = 0;
356218893Sdim
357198092Srdivacky  unsigned I = 0;
358198092Srdivacky  while (I < N) {
359199482Srdivacky    NamedDecl *D = Decls[I]->getUnderlyingDecl();
360199482Srdivacky    D = cast<NamedDecl>(D->getCanonicalDecl());
361198092Srdivacky
362212904Sdim    // Redeclarations of types via typedef can occur both within a scope
363212904Sdim    // and, through using declarations and directives, across scopes. There is
364212904Sdim    // no ambiguity if they all refer to the same type, so unique based on the
365212904Sdim    // canonical type.
366212904Sdim    if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
367212904Sdim      if (!TD->getDeclContext()->isRecord()) {
368212904Sdim        QualType T = SemaRef.Context.getTypeDeclType(TD);
369212904Sdim        if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
370212904Sdim          // The type is not unique; pull something off the back and continue
371212904Sdim          // at this index.
372212904Sdim          Decls[I] = Decls[--N];
373212904Sdim          continue;
374212904Sdim        }
375212904Sdim      }
376212904Sdim    }
377218893Sdim
378199482Srdivacky    if (!Unique.insert(D)) {
379198092Srdivacky      // If it's not unique, pull something off the back (and
380198092Srdivacky      // continue at this index).
381198092Srdivacky      Decls[I] = Decls[--N];
382212904Sdim      continue;
383218893Sdim    }
384218893Sdim
385212904Sdim    // Otherwise, do some decl type analysis and then continue.
386212904Sdim
387212904Sdim    if (isa<UnresolvedUsingValueDecl>(D)) {
388212904Sdim      HasUnresolved = true;
389212904Sdim    } else if (isa<TagDecl>(D)) {
390212904Sdim      if (HasTag)
391212904Sdim        Ambiguous = true;
392212904Sdim      UniqueTagIndex = I;
393212904Sdim      HasTag = true;
394212904Sdim    } else if (isa<FunctionTemplateDecl>(D)) {
395212904Sdim      HasFunction = true;
396212904Sdim      HasFunctionTemplate = true;
397212904Sdim    } else if (isa<FunctionDecl>(D)) {
398212904Sdim      HasFunction = true;
399198092Srdivacky    } else {
400212904Sdim      if (HasNonFunction)
401212904Sdim        Ambiguous = true;
402212904Sdim      HasNonFunction = true;
403193326Sed    }
404212904Sdim    I++;
405193326Sed  }
406193326Sed
407198092Srdivacky  // C++ [basic.scope.hiding]p2:
408198092Srdivacky  //   A class name or enumeration name can be hidden by the name of
409198092Srdivacky  //   an object, function, or enumerator declared in the same
410198092Srdivacky  //   scope. If a class or enumeration name and an object, function,
411198092Srdivacky  //   or enumerator are declared in the same scope (in any order)
412198092Srdivacky  //   with the same name, the class or enumeration name is hidden
413198092Srdivacky  //   wherever the object, function, or enumerator name is visible.
414198092Srdivacky  // But it's still an error if there are distinct tag types found,
415198092Srdivacky  // even if they're not visible. (ref?)
416200583Srdivacky  if (HideTags && HasTag && !Ambiguous &&
417218893Sdim      (HasFunction || HasNonFunction || HasUnresolved)) {
418218893Sdim    if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
419218893Sdim         Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
420218893Sdim      Decls[UniqueTagIndex] = Decls[--N];
421218893Sdim    else
422218893Sdim      Ambiguous = true;
423218893Sdim  }
424193326Sed
425198092Srdivacky  Decls.set_size(N);
426193326Sed
427200583Srdivacky  if (HasNonFunction && (HasFunction || HasUnresolved))
428198092Srdivacky    Ambiguous = true;
429193326Sed
430198092Srdivacky  if (Ambiguous)
431198092Srdivacky    setAmbiguous(LookupResult::AmbiguousReference);
432199482Srdivacky  else if (HasUnresolved)
433199482Srdivacky    ResultKind = LookupResult::FoundUnresolvedValue;
434199990Srdivacky  else if (N > 1 || HasFunctionTemplate)
435199482Srdivacky    ResultKind = LookupResult::FoundOverloaded;
436198092Srdivacky  else
437199482Srdivacky    ResultKind = LookupResult::Found;
438193326Sed}
439193326Sed
440199482Srdivackyvoid LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
441203955Srdivacky  CXXBasePaths::const_paths_iterator I, E;
442198092Srdivacky  DeclContext::lookup_iterator DI, DE;
443198092Srdivacky  for (I = P.begin(), E = P.end(); I != E; ++I)
444198092Srdivacky    for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
445198092Srdivacky      addDecl(*DI);
446193326Sed}
447193326Sed
448199482Srdivackyvoid LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
449198092Srdivacky  Paths = new CXXBasePaths;
450198092Srdivacky  Paths->swap(P);
451198092Srdivacky  addDeclsFromBasePaths(*Paths);
452198092Srdivacky  resolveKind();
453198092Srdivacky  setAmbiguous(AmbiguousBaseSubobjects);
454193326Sed}
455193326Sed
456199482Srdivackyvoid LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
457198092Srdivacky  Paths = new CXXBasePaths;
458198092Srdivacky  Paths->swap(P);
459198092Srdivacky  addDeclsFromBasePaths(*Paths);
460198092Srdivacky  resolveKind();
461198092Srdivacky  setAmbiguous(AmbiguousBaseSubobjectTypes);
462193326Sed}
463193326Sed
464226633Sdimvoid LookupResult::print(raw_ostream &Out) {
465198092Srdivacky  Out << Decls.size() << " result(s)";
466198092Srdivacky  if (isAmbiguous()) Out << ", ambiguous";
467198092Srdivacky  if (Paths) Out << ", base paths present";
468218893Sdim
469198092Srdivacky  for (iterator I = begin(), E = end(); I != E; ++I) {
470198092Srdivacky    Out << "\n";
471198092Srdivacky    (*I)->print(Out, 2);
472193326Sed  }
473193326Sed}
474193326Sed
475203955Srdivacky/// \brief Lookup a builtin function, when name lookup would otherwise
476203955Srdivacky/// fail.
477203955Srdivackystatic bool LookupBuiltin(Sema &S, LookupResult &R) {
478203955Srdivacky  Sema::LookupNameKind NameKind = R.getLookupKind();
479203955Srdivacky
480203955Srdivacky  // If we didn't find a use of this identifier, and if the identifier
481203955Srdivacky  // corresponds to a compiler builtin, create the decl object for the builtin
482203955Srdivacky  // now, injecting it into translation unit scope, and return it.
483203955Srdivacky  if (NameKind == Sema::LookupOrdinaryName ||
484203955Srdivacky      NameKind == Sema::LookupRedeclarationWithLinkage) {
485203955Srdivacky    IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
486203955Srdivacky    if (II) {
487203955Srdivacky      // If this is a builtin on this (or all) targets, create the decl.
488203955Srdivacky      if (unsigned BuiltinID = II->getBuiltinID()) {
489203955Srdivacky        // In C++, we don't have any predefined library functions like
490203955Srdivacky        // 'malloc'. Instead, we'll just error.
491203955Srdivacky        if (S.getLangOptions().CPlusPlus &&
492203955Srdivacky            S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
493203955Srdivacky          return false;
494203955Srdivacky
495218893Sdim        if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
496218893Sdim                                                 BuiltinID, S.TUScope,
497218893Sdim                                                 R.isForRedeclaration(),
498218893Sdim                                                 R.getNameLoc())) {
499203955Srdivacky          R.addDecl(D);
500218893Sdim          return true;
501218893Sdim        }
502218893Sdim
503218893Sdim        if (R.isForRedeclaration()) {
504218893Sdim          // If we're redeclaring this function anyway, forget that
505218893Sdim          // this was a builtin at all.
506218893Sdim          S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
507218893Sdim        }
508218893Sdim
509218893Sdim        return false;
510203955Srdivacky      }
511203955Srdivacky    }
512203955Srdivacky  }
513203955Srdivacky
514203955Srdivacky  return false;
515203955Srdivacky}
516203955Srdivacky
517210299Sed/// \brief Determine whether we can declare a special member function within
518210299Sed/// the class at this point.
519210299Sedstatic bool CanDeclareSpecialMemberFunction(ASTContext &Context,
520210299Sed                                            const CXXRecordDecl *Class) {
521212904Sdim  // Don't do it if the class is invalid.
522212904Sdim  if (Class->isInvalidDecl())
523212904Sdim    return false;
524218893Sdim
525210299Sed  // We need to have a definition for the class.
526210299Sed  if (!Class->getDefinition() || Class->isDependentContext())
527210299Sed    return false;
528218893Sdim
529210299Sed  // We can't be in the middle of defining the class.
530210299Sed  if (const RecordType *RecordTy
531210299Sed                        = Context.getTypeDeclType(Class)->getAs<RecordType>())
532210299Sed    return !RecordTy->isBeingDefined();
533218893Sdim
534210299Sed  return false;
535210299Sed}
536210299Sed
537210299Sedvoid Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
538210299Sed  if (!CanDeclareSpecialMemberFunction(Context, Class))
539210299Sed    return;
540210299Sed
541210299Sed  // If the default constructor has not yet been declared, do so now.
542223017Sdim  if (Class->needsImplicitDefaultConstructor())
543210299Sed    DeclareImplicitDefaultConstructor(Class);
544218893Sdim
545210299Sed  // If the copy constructor has not yet been declared, do so now.
546210299Sed  if (!Class->hasDeclaredCopyConstructor())
547210299Sed    DeclareImplicitCopyConstructor(Class);
548218893Sdim
549210299Sed  // If the copy assignment operator has not yet been declared, do so now.
550210299Sed  if (!Class->hasDeclaredCopyAssignment())
551210299Sed    DeclareImplicitCopyAssignment(Class);
552210299Sed
553226633Sdim  if (getLangOptions().CPlusPlus0x) {
554226633Sdim    // If the move constructor has not yet been declared, do so now.
555226633Sdim    if (Class->needsImplicitMoveConstructor())
556226633Sdim      DeclareImplicitMoveConstructor(Class); // might not actually do it
557226633Sdim
558226633Sdim    // If the move assignment operator has not yet been declared, do so now.
559226633Sdim    if (Class->needsImplicitMoveAssignment())
560226633Sdim      DeclareImplicitMoveAssignment(Class); // might not actually do it
561226633Sdim  }
562226633Sdim
563210299Sed  // If the destructor has not yet been declared, do so now.
564210299Sed  if (!Class->hasDeclaredDestructor())
565218893Sdim    DeclareImplicitDestructor(Class);
566210299Sed}
567210299Sed
568218893Sdim/// \brief Determine whether this is the name of an implicitly-declared
569210299Sed/// special member function.
570210299Sedstatic bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
571210299Sed  switch (Name.getNameKind()) {
572210299Sed  case DeclarationName::CXXConstructorName:
573210299Sed  case DeclarationName::CXXDestructorName:
574210299Sed    return true;
575218893Sdim
576210299Sed  case DeclarationName::CXXOperatorName:
577210299Sed    return Name.getCXXOverloadedOperator() == OO_Equal;
578218893Sdim
579210299Sed  default:
580218893Sdim    break;
581210299Sed  }
582218893Sdim
583210299Sed  return false;
584210299Sed}
585210299Sed
586210299Sed/// \brief If there are any implicit member functions with the given name
587210299Sed/// that need to be declared in the given declaration context, do so.
588218893Sdimstatic void DeclareImplicitMemberFunctionsWithName(Sema &S,
589210299Sed                                                   DeclarationName Name,
590210299Sed                                                   const DeclContext *DC) {
591210299Sed  if (!DC)
592210299Sed    return;
593218893Sdim
594210299Sed  switch (Name.getNameKind()) {
595210299Sed  case DeclarationName::CXXConstructorName:
596210299Sed    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
597210299Sed      if (Record->getDefinition() &&
598210299Sed          CanDeclareSpecialMemberFunction(S.Context, Record)) {
599226633Sdim        CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
600223017Sdim        if (Record->needsImplicitDefaultConstructor())
601226633Sdim          S.DeclareImplicitDefaultConstructor(Class);
602210299Sed        if (!Record->hasDeclaredCopyConstructor())
603226633Sdim          S.DeclareImplicitCopyConstructor(Class);
604226633Sdim        if (S.getLangOptions().CPlusPlus0x &&
605226633Sdim            Record->needsImplicitMoveConstructor())
606226633Sdim          S.DeclareImplicitMoveConstructor(Class);
607210299Sed      }
608210299Sed    break;
609218893Sdim
610210299Sed  case DeclarationName::CXXDestructorName:
611210299Sed    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
612210299Sed      if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
613210299Sed          CanDeclareSpecialMemberFunction(S.Context, Record))
614210299Sed        S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
615210299Sed    break;
616218893Sdim
617210299Sed  case DeclarationName::CXXOperatorName:
618210299Sed    if (Name.getCXXOverloadedOperator() != OO_Equal)
619210299Sed      break;
620218893Sdim
621226633Sdim    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
622226633Sdim      if (Record->getDefinition() &&
623226633Sdim          CanDeclareSpecialMemberFunction(S.Context, Record)) {
624226633Sdim        CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
625226633Sdim        if (!Record->hasDeclaredCopyAssignment())
626226633Sdim          S.DeclareImplicitCopyAssignment(Class);
627226633Sdim        if (S.getLangOptions().CPlusPlus0x &&
628226633Sdim            Record->needsImplicitMoveAssignment())
629226633Sdim          S.DeclareImplicitMoveAssignment(Class);
630226633Sdim      }
631226633Sdim    }
632210299Sed    break;
633218893Sdim
634210299Sed  default:
635218893Sdim    break;
636210299Sed  }
637210299Sed}
638210299Sed
639198092Srdivacky// Adds all qualifying matches for a name within a decl context to the
640198092Srdivacky// given lookup result.  Returns true if any matches were found.
641203955Srdivackystatic bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
642198092Srdivacky  bool Found = false;
643193326Sed
644210299Sed  // Lazily declare C++ special member functions.
645210299Sed  if (S.getLangOptions().CPlusPlus)
646210299Sed    DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
647218893Sdim
648210299Sed  // Perform lookup into this declaration context.
649199482Srdivacky  DeclContext::lookup_const_iterator I, E;
650202379Srdivacky  for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
651202879Srdivacky    NamedDecl *D = *I;
652202879Srdivacky    if (R.isAcceptableDecl(D)) {
653202879Srdivacky      R.addDecl(D);
654202379Srdivacky      Found = true;
655202379Srdivacky    }
656202379Srdivacky  }
657193326Sed
658203955Srdivacky  if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
659203955Srdivacky    return true;
660203955Srdivacky
661202379Srdivacky  if (R.getLookupName().getNameKind()
662203955Srdivacky        != DeclarationName::CXXConversionFunctionName ||
663203955Srdivacky      R.getLookupName().getCXXNameType()->isDependentType() ||
664203955Srdivacky      !isa<CXXRecordDecl>(DC))
665203955Srdivacky    return Found;
666202379Srdivacky
667203955Srdivacky  // C++ [temp.mem]p6:
668218893Sdim  //   A specialization of a conversion function template is not found by
669203955Srdivacky  //   name lookup. Instead, any conversion function templates visible in the
670203955Srdivacky  //   context of the use are considered. [...]
671203955Srdivacky  const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
672226633Sdim  if (!Record->isCompleteDefinition())
673203955Srdivacky    return Found;
674202379Srdivacky
675203955Srdivacky  const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
676218893Sdim  for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
677203955Srdivacky         UEnd = Unresolved->end(); U != UEnd; ++U) {
678203955Srdivacky    FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
679203955Srdivacky    if (!ConvTemplate)
680203955Srdivacky      continue;
681218893Sdim
682203955Srdivacky    // When we're performing lookup for the purposes of redeclaration, just
683218893Sdim    // add the conversion function template. When we deduce template
684218893Sdim    // arguments for specializations, we'll end up unifying the return
685203955Srdivacky    // type of the new declaration with the type of the function template.
686203955Srdivacky    if (R.isForRedeclaration()) {
687203955Srdivacky      R.addDecl(ConvTemplate);
688203955Srdivacky      Found = true;
689203955Srdivacky      continue;
690202379Srdivacky    }
691218893Sdim
692203955Srdivacky    // C++ [temp.mem]p6:
693218893Sdim    //   [...] For each such operator, if argument deduction succeeds
694218893Sdim    //   (14.9.2.3), the resulting specialization is used as if found by
695203955Srdivacky    //   name lookup.
696203955Srdivacky    //
697203955Srdivacky    // When referencing a conversion function for any purpose other than
698203955Srdivacky    // a redeclaration (such that we'll be building an expression with the
699218893Sdim    // result), perform template argument deduction and place the
700203955Srdivacky    // specialization into the result set. We do this to avoid forcing all
701203955Srdivacky    // callers to perform special deduction for conversion functions.
702212904Sdim    TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
703203955Srdivacky    FunctionDecl *Specialization = 0;
704218893Sdim
705218893Sdim    const FunctionProtoType *ConvProto
706203955Srdivacky      = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
707203955Srdivacky    assert(ConvProto && "Nonsensical conversion function template type");
708203955Srdivacky
709203955Srdivacky    // Compute the type of the function that we would expect the conversion
710203955Srdivacky    // function to have, if it were to match the name given.
711203955Srdivacky    // FIXME: Calling convention!
712218893Sdim    FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
713218893Sdim    EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
714221345Sdim    EPI.ExceptionSpecType = EST_None;
715218893Sdim    EPI.NumExceptions = 0;
716203955Srdivacky    QualType ExpectedType
717203955Srdivacky      = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
718218893Sdim                                            0, 0, EPI);
719218893Sdim
720203955Srdivacky    // Perform template argument deduction against the type that we would
721203955Srdivacky    // expect the function to have.
722203955Srdivacky    if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
723203955Srdivacky                                            Specialization, Info)
724203955Srdivacky          == Sema::TDK_Success) {
725203955Srdivacky      R.addDecl(Specialization);
726203955Srdivacky      Found = true;
727203955Srdivacky    }
728202379Srdivacky  }
729203955Srdivacky
730198092Srdivacky  return Found;
731193326Sed}
732193326Sed
733199482Srdivacky// Performs C++ unqualified lookup into the given file context.
734198092Srdivackystatic bool
735218893SdimCppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
736203955Srdivacky                   DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
737193326Sed
738193326Sed  assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
739193326Sed
740199482Srdivacky  // Perform direct name lookup into the LookupCtx.
741203955Srdivacky  bool Found = LookupDirect(S, R, NS);
742193326Sed
743199482Srdivacky  // Perform direct name lookup into the namespaces nominated by the
744199482Srdivacky  // using directives whose common ancestor is this namespace.
745199482Srdivacky  UnqualUsingDirectiveSet::const_iterator UI, UEnd;
746199482Srdivacky  llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
747198092Srdivacky
748199482Srdivacky  for (; UI != UEnd; ++UI)
749203955Srdivacky    if (LookupDirect(S, R, UI->getNominatedNamespace()))
750199482Srdivacky      Found = true;
751198092Srdivacky
752198092Srdivacky  R.resolveKind();
753198092Srdivacky
754198092Srdivacky  return Found;
755193326Sed}
756193326Sed
757193326Sedstatic bool isNamespaceOrTranslationUnitScope(Scope *S) {
758193326Sed  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
759193326Sed    return Ctx->isFileContext();
760193326Sed  return false;
761193326Sed}
762193326Sed
763205219Srdivacky// Find the next outer declaration context from this scope. This
764205219Srdivacky// routine actually returns the semantic outer context, which may
765205219Srdivacky// differ from the lexical context (encoded directly in the Scope
766205219Srdivacky// stack) when we are parsing a member of a class template. In this
767205219Srdivacky// case, the second element of the pair will be true, to indicate that
768205219Srdivacky// name lookup should continue searching in this semantic context when
769205219Srdivacky// it leaves the current template parameter scope.
770205219Srdivackystatic std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
771205219Srdivacky  DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
772205219Srdivacky  DeclContext *Lexical = 0;
773218893Sdim  for (Scope *OuterS = S->getParent(); OuterS;
774205219Srdivacky       OuterS = OuterS->getParent()) {
775205219Srdivacky    if (OuterS->getEntity()) {
776205219Srdivacky      Lexical = static_cast<DeclContext *>(OuterS->getEntity());
777205219Srdivacky      break;
778205219Srdivacky    }
779205219Srdivacky  }
780205219Srdivacky
781205219Srdivacky  // C++ [temp.local]p8:
782205219Srdivacky  //   In the definition of a member of a class template that appears
783205219Srdivacky  //   outside of the namespace containing the class template
784205219Srdivacky  //   definition, the name of a template-parameter hides the name of
785205219Srdivacky  //   a member of this namespace.
786205219Srdivacky  //
787205219Srdivacky  // Example:
788205219Srdivacky  //
789218893Sdim  //   namespace N {
790218893Sdim  //     class C { };
791205219Srdivacky  //
792205219Srdivacky  //     template<class T> class B {
793205219Srdivacky  //       void f(T);
794218893Sdim  //     };
795205219Srdivacky  //   }
796205219Srdivacky  //
797205219Srdivacky  //   template<class C> void N::B<C>::f(C) {
798205219Srdivacky  //     C b;  // C is the template parameter, not N::C
799205219Srdivacky  //   }
800205219Srdivacky  //
801205219Srdivacky  // In this example, the lexical context we return is the
802205219Srdivacky  // TranslationUnit, while the semantic context is the namespace N.
803218893Sdim  if (!Lexical || !DC || !S->getParent() ||
804205219Srdivacky      !S->getParent()->isTemplateParamScope())
805205219Srdivacky    return std::make_pair(Lexical, false);
806205219Srdivacky
807218893Sdim  // Find the outermost template parameter scope.
808205219Srdivacky  // For the example, this is the scope for the template parameters of
809205219Srdivacky  // template<class C>.
810205219Srdivacky  Scope *OutermostTemplateScope = S->getParent();
811205219Srdivacky  while (OutermostTemplateScope->getParent() &&
812205219Srdivacky         OutermostTemplateScope->getParent()->isTemplateParamScope())
813205219Srdivacky    OutermostTemplateScope = OutermostTemplateScope->getParent();
814218893Sdim
815205219Srdivacky  // Find the namespace context in which the original scope occurs. In
816205219Srdivacky  // the example, this is namespace N.
817205219Srdivacky  DeclContext *Semantic = DC;
818205219Srdivacky  while (!Semantic->isFileContext())
819205219Srdivacky    Semantic = Semantic->getParent();
820218893Sdim
821205219Srdivacky  // Find the declaration context just outside of the template
822205219Srdivacky  // parameter scope. This is the context in which the template is
823205219Srdivacky  // being lexically declaration (a namespace context). In the
824205219Srdivacky  // example, this is the global scope.
825205219Srdivacky  if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
826205219Srdivacky      Lexical->Encloses(Semantic))
827205219Srdivacky    return std::make_pair(Semantic, true);
828205219Srdivacky
829205219Srdivacky  return std::make_pair(Lexical, false);
830198092Srdivacky}
831198092Srdivacky
832199482Srdivackybool Sema::CppLookupName(LookupResult &R, Scope *S) {
833201361Srdivacky  assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
834198092Srdivacky
835199482Srdivacky  DeclarationName Name = R.getLookupName();
836199482Srdivacky
837210299Sed  // If this is the name of an implicitly-declared special member function,
838210299Sed  // go through the scope stack to implicitly declare
839210299Sed  if (isImplicitlyDeclaredMemberFunctionName(Name)) {
840210299Sed    for (Scope *PreS = S; PreS; PreS = PreS->getParent())
841210299Sed      if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
842210299Sed        DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
843210299Sed  }
844218893Sdim
845210299Sed  // Implicitly declare member functions with the name we're looking for, if in
846210299Sed  // fact we are in a scope where it matters.
847210299Sed
848193326Sed  Scope *Initial = S;
849198092Srdivacky  IdentifierResolver::iterator
850193326Sed    I = IdResolver.begin(Name),
851193326Sed    IEnd = IdResolver.end();
852193326Sed
853193326Sed  // First we lookup local scope.
854193326Sed  // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
855193326Sed  // ...During unqualified name lookup (3.4.1), the names appear as if
856193326Sed  // they were declared in the nearest enclosing namespace which contains
857193326Sed  // both the using-directive and the nominated namespace.
858198092Srdivacky  // [Note: in this context, "contains" means "contains directly or
859198092Srdivacky  // indirectly".
860193326Sed  //
861193326Sed  // For example:
862193326Sed  // namespace A { int i; }
863193326Sed  // void foo() {
864193326Sed  //   int i;
865193326Sed  //   {
866193326Sed  //     using namespace A;
867193326Sed  //     ++i; // finds local 'i', A::i appears at global scope
868193326Sed  //   }
869193326Sed  // }
870193326Sed  //
871205219Srdivacky  DeclContext *OutsideOfTemplateParamDC = 0;
872193326Sed  for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
873208600Srdivacky    DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
874208600Srdivacky
875193326Sed    // Check whether the IdResolver has anything in this scope.
876198092Srdivacky    bool Found = false;
877212904Sdim    for (; I != IEnd && S->isDeclScope(*I); ++I) {
878201361Srdivacky      if (R.isAcceptableDecl(*I)) {
879198092Srdivacky        Found = true;
880198092Srdivacky        R.addDecl(*I);
881193326Sed      }
882193326Sed    }
883198092Srdivacky    if (Found) {
884198092Srdivacky      R.resolveKind();
885208600Srdivacky      if (S->isClassScope())
886208600Srdivacky        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
887208600Srdivacky          R.setNamingClass(Record);
888198092Srdivacky      return true;
889198092Srdivacky    }
890198092Srdivacky
891205219Srdivacky    if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
892205219Srdivacky        S->getParent() && !S->getParent()->isTemplateParamScope()) {
893205219Srdivacky      // We've just searched the last template parameter scope and
894205219Srdivacky      // found nothing, so look into the the contexts between the
895205219Srdivacky      // lexical and semantic declaration contexts returned by
896205219Srdivacky      // findOuterContext(). This implements the name lookup behavior
897205219Srdivacky      // of C++ [temp.local]p8.
898205219Srdivacky      Ctx = OutsideOfTemplateParamDC;
899205219Srdivacky      OutsideOfTemplateParamDC = 0;
900205219Srdivacky    }
901205219Srdivacky
902205219Srdivacky    if (Ctx) {
903205219Srdivacky      DeclContext *OuterCtx;
904205219Srdivacky      bool SearchAfterTemplateScope;
905205219Srdivacky      llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
906205219Srdivacky      if (SearchAfterTemplateScope)
907205219Srdivacky        OutsideOfTemplateParamDC = OuterCtx;
908205219Srdivacky
909205219Srdivacky      for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
910204643Srdivacky        // We do not directly look into transparent contexts, since
911204643Srdivacky        // those entities will be found in the nearest enclosing
912204643Srdivacky        // non-transparent context.
913204643Srdivacky        if (Ctx->isTransparentContext())
914198092Srdivacky          continue;
915204643Srdivacky
916204643Srdivacky        // We do not look directly into function or method contexts,
917204643Srdivacky        // since all of the local variables and parameters of the
918204643Srdivacky        // function/method are present within the Scope.
919204643Srdivacky        if (Ctx->isFunctionOrMethod()) {
920204643Srdivacky          // If we have an Objective-C instance method, look for ivars
921204643Srdivacky          // in the corresponding interface.
922204643Srdivacky          if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
923204643Srdivacky            if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
924204643Srdivacky              if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
925204643Srdivacky                ObjCInterfaceDecl *ClassDeclared;
926204643Srdivacky                if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
927218893Sdim                                                 Name.getAsIdentifierInfo(),
928204643Srdivacky                                                             ClassDeclared)) {
929204643Srdivacky                  if (R.isAcceptableDecl(Ivar)) {
930204643Srdivacky                    R.addDecl(Ivar);
931204643Srdivacky                    R.resolveKind();
932204643Srdivacky                    return true;
933204643Srdivacky                  }
934204643Srdivacky                }
935204643Srdivacky              }
936204643Srdivacky          }
937204643Srdivacky
938204643Srdivacky          continue;
939204643Srdivacky        }
940204643Srdivacky
941198092Srdivacky        // Perform qualified name lookup into this context.
942198092Srdivacky        // FIXME: In some cases, we know that every name that could be found by
943198092Srdivacky        // this qualified name lookup will also be on the identifier chain. For
944198092Srdivacky        // example, inside a class without any base classes, we never need to
945198092Srdivacky        // perform qualified lookup because all of the members are on top of the
946198092Srdivacky        // identifier chain.
947202379Srdivacky        if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
948198092Srdivacky          return true;
949193326Sed      }
950193326Sed    }
951193326Sed  }
952193326Sed
953199482Srdivacky  // Stop if we ran out of scopes.
954199482Srdivacky  // FIXME:  This really, really shouldn't be happening.
955199482Srdivacky  if (!S) return false;
956199482Srdivacky
957218893Sdim  // If we are looking for members, no need to look into global/namespace scope.
958218893Sdim  if (R.getLookupKind() == LookupMemberName)
959218893Sdim    return false;
960218893Sdim
961193326Sed  // Collect UsingDirectiveDecls in all scopes, and recursively all
962193326Sed  // nominated namespaces by those using-directives.
963199482Srdivacky  //
964193326Sed  // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
965193326Sed  // don't build it for each lookup!
966193326Sed
967199482Srdivacky  UnqualUsingDirectiveSet UDirs;
968199482Srdivacky  UDirs.visitScopeChain(Initial, S);
969199482Srdivacky  UDirs.done();
970193326Sed
971193326Sed  // Lookup namespace scope, and global scope.
972193326Sed  // Unqualified name lookup in C++ requires looking into scopes
973193326Sed  // that aren't strictly lexical, and therefore we walk through the
974193326Sed  // context as well as walking through the scopes.
975193326Sed
976193326Sed  for (; S; S = S->getParent()) {
977193326Sed    // Check whether the IdResolver has anything in this scope.
978198092Srdivacky    bool Found = false;
979212904Sdim    for (; I != IEnd && S->isDeclScope(*I); ++I) {
980201361Srdivacky      if (R.isAcceptableDecl(*I)) {
981193326Sed        // We found something.  Look for anything else in our scope
982193326Sed        // with this same name and in an acceptable identifier
983193326Sed        // namespace, so that we can construct an overload set if we
984193326Sed        // need to.
985198092Srdivacky        Found = true;
986198092Srdivacky        R.addDecl(*I);
987193326Sed      }
988193326Sed    }
989193326Sed
990208600Srdivacky    if (Found && S->isTemplateParamScope()) {
991208600Srdivacky      R.resolveKind();
992208600Srdivacky      return true;
993208600Srdivacky    }
994193326Sed
995208600Srdivacky    DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
996208600Srdivacky    if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
997208600Srdivacky        S->getParent() && !S->getParent()->isTemplateParamScope()) {
998208600Srdivacky      // We've just searched the last template parameter scope and
999208600Srdivacky      // found nothing, so look into the the contexts between the
1000208600Srdivacky      // lexical and semantic declaration contexts returned by
1001208600Srdivacky      // findOuterContext(). This implements the name lookup behavior
1002208600Srdivacky      // of C++ [temp.local]p8.
1003208600Srdivacky      Ctx = OutsideOfTemplateParamDC;
1004208600Srdivacky      OutsideOfTemplateParamDC = 0;
1005203955Srdivacky    }
1006218893Sdim
1007208600Srdivacky    if (Ctx) {
1008208600Srdivacky      DeclContext *OuterCtx;
1009208600Srdivacky      bool SearchAfterTemplateScope;
1010208600Srdivacky      llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1011208600Srdivacky      if (SearchAfterTemplateScope)
1012208600Srdivacky        OutsideOfTemplateParamDC = OuterCtx;
1013203955Srdivacky
1014208600Srdivacky      for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1015208600Srdivacky        // We do not directly look into transparent contexts, since
1016208600Srdivacky        // those entities will be found in the nearest enclosing
1017208600Srdivacky        // non-transparent context.
1018208600Srdivacky        if (Ctx->isTransparentContext())
1019208600Srdivacky          continue;
1020218893Sdim
1021208600Srdivacky        // If we have a context, and it's not a context stashed in the
1022208600Srdivacky        // template parameter scope for an out-of-line definition, also
1023208600Srdivacky        // look into that context.
1024208600Srdivacky        if (!(Found && S && S->isTemplateParamScope())) {
1025208600Srdivacky          assert(Ctx->isFileContext() &&
1026208600Srdivacky              "We should have been looking only at file context here already.");
1027218893Sdim
1028208600Srdivacky          // Look into context considering using-directives.
1029208600Srdivacky          if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1030208600Srdivacky            Found = true;
1031208600Srdivacky        }
1032218893Sdim
1033208600Srdivacky        if (Found) {
1034208600Srdivacky          R.resolveKind();
1035208600Srdivacky          return true;
1036208600Srdivacky        }
1037218893Sdim
1038208600Srdivacky        if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1039208600Srdivacky          return false;
1040208600Srdivacky      }
1041198092Srdivacky    }
1042198092Srdivacky
1043203955Srdivacky    if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1044198092Srdivacky      return false;
1045193326Sed  }
1046193326Sed
1047198092Srdivacky  return !R.empty();
1048193326Sed}
1049193326Sed
1050193326Sed/// @brief Perform unqualified name lookup starting from a given
1051193326Sed/// scope.
1052193326Sed///
1053193326Sed/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1054193326Sed/// used to find names within the current scope. For example, 'x' in
1055193326Sed/// @code
1056193326Sed/// int x;
1057193326Sed/// int f() {
1058193326Sed///   return x; // unqualified name look finds 'x' in the global scope
1059193326Sed/// }
1060193326Sed/// @endcode
1061193326Sed///
1062193326Sed/// Different lookup criteria can find different names. For example, a
1063193326Sed/// particular scope can have both a struct and a function of the same
1064193326Sed/// name, and each can be found by certain lookup criteria. For more
1065193326Sed/// information about lookup criteria, see the documentation for the
1066193326Sed/// class LookupCriteria.
1067193326Sed///
1068193326Sed/// @param S        The scope from which unqualified name lookup will
1069193326Sed/// begin. If the lookup criteria permits, name lookup may also search
1070193326Sed/// in the parent scopes.
1071193326Sed///
1072193326Sed/// @param Name     The name of the entity that we are searching for.
1073193326Sed///
1074193326Sed/// @param Loc      If provided, the source location where we're performing
1075198092Srdivacky/// name lookup. At present, this is only used to produce diagnostics when
1076193326Sed/// C library functions (like "malloc") are implicitly declared.
1077193326Sed///
1078193326Sed/// @returns The result of name lookup, which includes zero or more
1079193326Sed/// declarations and possibly additional information used to diagnose
1080193326Sed/// ambiguities.
1081199482Srdivackybool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1082199482Srdivacky  DeclarationName Name = R.getLookupName();
1083198092Srdivacky  if (!Name) return false;
1084193326Sed
1085199482Srdivacky  LookupNameKind NameKind = R.getLookupKind();
1086199482Srdivacky
1087193326Sed  if (!getLangOptions().CPlusPlus) {
1088193326Sed    // Unqualified name lookup in C/Objective-C is purely lexical, so
1089193326Sed    // search in the declarations attached to the name.
1090201361Srdivacky    if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1091193326Sed      // Find the nearest non-transparent declaration scope.
1092193326Sed      while (!(S->getFlags() & Scope::DeclScope) ||
1093198092Srdivacky             (S->getEntity() &&
1094193326Sed              static_cast<DeclContext *>(S->getEntity())
1095193326Sed                ->isTransparentContext()))
1096193326Sed        S = S->getParent();
1097201361Srdivacky    }
1098193326Sed
1099201361Srdivacky    unsigned IDNS = R.getIdentifierNamespace();
1100193326Sed
1101193326Sed    // Scan up the scope chain looking for a decl that matches this
1102193326Sed    // identifier that is in the appropriate namespace.  This search
1103193326Sed    // should not take long, as shadowing of names is uncommon, and
1104193326Sed    // deep shadowing is extremely uncommon.
1105193326Sed    bool LeftStartingScope = false;
1106193326Sed
1107193326Sed    for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1108198092Srdivacky                                   IEnd = IdResolver.end();
1109193326Sed         I != IEnd; ++I)
1110193326Sed      if ((*I)->isInIdentifierNamespace(IDNS)) {
1111193326Sed        if (NameKind == LookupRedeclarationWithLinkage) {
1112193326Sed          // Determine whether this (or a previous) declaration is
1113193326Sed          // out-of-scope.
1114212904Sdim          if (!LeftStartingScope && !S->isDeclScope(*I))
1115193326Sed            LeftStartingScope = true;
1116193326Sed
1117193326Sed          // If we found something outside of our starting scope that
1118193326Sed          // does not have linkage, skip it.
1119193326Sed          if (LeftStartingScope && !((*I)->hasLinkage()))
1120193326Sed            continue;
1121193326Sed        }
1122224145Sdim        else if (NameKind == LookupObjCImplicitSelfParam &&
1123224145Sdim                 !isa<ImplicitParamDecl>(*I))
1124224145Sdim          continue;
1125224145Sdim
1126198092Srdivacky        R.addDecl(*I);
1127198092Srdivacky
1128195341Sed        if ((*I)->getAttr<OverloadableAttr>()) {
1129193326Sed          // If this declaration has the "overloadable" attribute, we
1130193326Sed          // might have a set of overloaded functions.
1131193326Sed
1132193326Sed          // Figure out what scope the identifier is in.
1133193326Sed          while (!(S->getFlags() & Scope::DeclScope) ||
1134212904Sdim                 !S->isDeclScope(*I))
1135193326Sed            S = S->getParent();
1136193326Sed
1137193326Sed          // Find the last declaration in this scope (with the same
1138193326Sed          // name, naturally).
1139193326Sed          IdentifierResolver::iterator LastI = I;
1140193326Sed          for (++LastI; LastI != IEnd; ++LastI) {
1141212904Sdim            if (!S->isDeclScope(*LastI))
1142193326Sed              break;
1143198092Srdivacky            R.addDecl(*LastI);
1144193326Sed          }
1145193326Sed        }
1146193326Sed
1147198092Srdivacky        R.resolveKind();
1148198092Srdivacky
1149198092Srdivacky        return true;
1150193326Sed      }
1151193326Sed  } else {
1152193326Sed    // Perform C++ unqualified name lookup.
1153199482Srdivacky    if (CppLookupName(R, S))
1154198092Srdivacky      return true;
1155193326Sed  }
1156193326Sed
1157193326Sed  // If we didn't find a use of this identifier, and if the identifier
1158193326Sed  // corresponds to a compiler builtin, create the decl object for the builtin
1159193326Sed  // now, injecting it into translation unit scope, and return it.
1160221345Sdim  if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1161221345Sdim    return true;
1162193326Sed
1163219077Sdim  // If we didn't find a use of this identifier, the ExternalSource
1164219077Sdim  // may be able to handle the situation.
1165219077Sdim  // Note: some lookup failures are expected!
1166219077Sdim  // See e.g. R.isForRedeclaration().
1167219077Sdim  return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1168193326Sed}
1169193326Sed
1170198092Srdivacky/// @brief Perform qualified name lookup in the namespaces nominated by
1171198092Srdivacky/// using directives by the given context.
1172198092Srdivacky///
1173198092Srdivacky/// C++98 [namespace.qual]p2:
1174198092Srdivacky///   Given X::m (where X is a user-declared namespace), or given ::m
1175198092Srdivacky///   (where X is the global namespace), let S be the set of all
1176198092Srdivacky///   declarations of m in X and in the transitive closure of all
1177198092Srdivacky///   namespaces nominated by using-directives in X and its used
1178198092Srdivacky///   namespaces, except that using-directives are ignored in any
1179198092Srdivacky///   namespace, including X, directly containing one or more
1180198092Srdivacky///   declarations of m. No namespace is searched more than once in
1181198092Srdivacky///   the lookup of a name. If S is the empty set, the program is
1182198092Srdivacky///   ill-formed. Otherwise, if S has exactly one member, or if the
1183198092Srdivacky///   context of the reference is a using-declaration
1184198092Srdivacky///   (namespace.udecl), S is the required set of declarations of
1185198092Srdivacky///   m. Otherwise if the use of m is not one that allows a unique
1186198092Srdivacky///   declaration to be chosen from S, the program is ill-formed.
1187198092Srdivacky/// C++98 [namespace.qual]p5:
1188198092Srdivacky///   During the lookup of a qualified namespace member name, if the
1189198092Srdivacky///   lookup finds more than one declaration of the member, and if one
1190198092Srdivacky///   declaration introduces a class name or enumeration name and the
1191198092Srdivacky///   other declarations either introduce the same object, the same
1192198092Srdivacky///   enumerator or a set of functions, the non-type name hides the
1193198092Srdivacky///   class or enumeration name if and only if the declarations are
1194198092Srdivacky///   from the same namespace; otherwise (the declarations are from
1195198092Srdivacky///   different namespaces), the program is ill-formed.
1196203955Srdivackystatic bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1197199482Srdivacky                                                 DeclContext *StartDC) {
1198198092Srdivacky  assert(StartDC->isFileContext() && "start context is not a file context");
1199198092Srdivacky
1200198092Srdivacky  DeclContext::udir_iterator I = StartDC->using_directives_begin();
1201198092Srdivacky  DeclContext::udir_iterator E = StartDC->using_directives_end();
1202198092Srdivacky
1203198092Srdivacky  if (I == E) return false;
1204198092Srdivacky
1205198092Srdivacky  // We have at least added all these contexts to the queue.
1206198092Srdivacky  llvm::DenseSet<DeclContext*> Visited;
1207198092Srdivacky  Visited.insert(StartDC);
1208198092Srdivacky
1209198092Srdivacky  // We have not yet looked into these namespaces, much less added
1210198092Srdivacky  // their "using-children" to the queue.
1211226633Sdim  SmallVector<NamespaceDecl*, 8> Queue;
1212198092Srdivacky
1213198092Srdivacky  // We have already looked into the initial namespace; seed the queue
1214198092Srdivacky  // with its using-children.
1215198092Srdivacky  for (; I != E; ++I) {
1216199482Srdivacky    NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
1217198092Srdivacky    if (Visited.insert(ND).second)
1218198092Srdivacky      Queue.push_back(ND);
1219198092Srdivacky  }
1220198092Srdivacky
1221198092Srdivacky  // The easiest way to implement the restriction in [namespace.qual]p5
1222198092Srdivacky  // is to check whether any of the individual results found a tag
1223198092Srdivacky  // and, if so, to declare an ambiguity if the final result is not
1224198092Srdivacky  // a tag.
1225198092Srdivacky  bool FoundTag = false;
1226198092Srdivacky  bool FoundNonTag = false;
1227198092Srdivacky
1228199482Srdivacky  LookupResult LocalR(LookupResult::Temporary, R);
1229198092Srdivacky
1230198092Srdivacky  bool Found = false;
1231198092Srdivacky  while (!Queue.empty()) {
1232198092Srdivacky    NamespaceDecl *ND = Queue.back();
1233198092Srdivacky    Queue.pop_back();
1234198092Srdivacky
1235198092Srdivacky    // We go through some convolutions here to avoid copying results
1236198092Srdivacky    // between LookupResults.
1237198092Srdivacky    bool UseLocal = !R.empty();
1238199482Srdivacky    LookupResult &DirectR = UseLocal ? LocalR : R;
1239203955Srdivacky    bool FoundDirect = LookupDirect(S, DirectR, ND);
1240198092Srdivacky
1241198092Srdivacky    if (FoundDirect) {
1242198092Srdivacky      // First do any local hiding.
1243198092Srdivacky      DirectR.resolveKind();
1244198092Srdivacky
1245198092Srdivacky      // If the local result is a tag, remember that.
1246198092Srdivacky      if (DirectR.isSingleTagDecl())
1247198092Srdivacky        FoundTag = true;
1248198092Srdivacky      else
1249198092Srdivacky        FoundNonTag = true;
1250198092Srdivacky
1251198092Srdivacky      // Append the local results to the total results if necessary.
1252198092Srdivacky      if (UseLocal) {
1253198092Srdivacky        R.addAllDecls(LocalR);
1254198092Srdivacky        LocalR.clear();
1255198092Srdivacky      }
1256198092Srdivacky    }
1257198092Srdivacky
1258198092Srdivacky    // If we find names in this namespace, ignore its using directives.
1259198092Srdivacky    if (FoundDirect) {
1260198092Srdivacky      Found = true;
1261198092Srdivacky      continue;
1262198092Srdivacky    }
1263198092Srdivacky
1264198092Srdivacky    for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1265198092Srdivacky      NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1266198092Srdivacky      if (Visited.insert(Nom).second)
1267198092Srdivacky        Queue.push_back(Nom);
1268198092Srdivacky    }
1269198092Srdivacky  }
1270198092Srdivacky
1271198092Srdivacky  if (Found) {
1272198092Srdivacky    if (FoundTag && FoundNonTag)
1273198092Srdivacky      R.setAmbiguousQualifiedTagHiding();
1274198092Srdivacky    else
1275198092Srdivacky      R.resolveKind();
1276198092Srdivacky  }
1277198092Srdivacky
1278198092Srdivacky  return Found;
1279198092Srdivacky}
1280198092Srdivacky
1281212904Sdim/// \brief Callback that looks for any member of a class with the given name.
1282218893Sdimstatic bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1283212904Sdim                            CXXBasePath &Path,
1284212904Sdim                            void *Name) {
1285212904Sdim  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1286218893Sdim
1287212904Sdim  DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1288212904Sdim  Path.Decls = BaseRecord->lookup(N);
1289212904Sdim  return Path.Decls.first != Path.Decls.second;
1290212904Sdim}
1291212904Sdim
1292218893Sdim/// \brief Determine whether the given set of member declarations contains only
1293218893Sdim/// static members, nested types, and enumerators.
1294218893Sdimtemplate<typename InputIterator>
1295218893Sdimstatic bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1296218893Sdim  Decl *D = (*First)->getUnderlyingDecl();
1297218893Sdim  if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1298218893Sdim    return true;
1299218893Sdim
1300218893Sdim  if (isa<CXXMethodDecl>(D)) {
1301218893Sdim    // Determine whether all of the methods are static.
1302218893Sdim    bool AllMethodsAreStatic = true;
1303218893Sdim    for(; First != Last; ++First) {
1304218893Sdim      D = (*First)->getUnderlyingDecl();
1305218893Sdim
1306218893Sdim      if (!isa<CXXMethodDecl>(D)) {
1307218893Sdim        assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1308218893Sdim        break;
1309218893Sdim      }
1310218893Sdim
1311218893Sdim      if (!cast<CXXMethodDecl>(D)->isStatic()) {
1312218893Sdim        AllMethodsAreStatic = false;
1313218893Sdim        break;
1314218893Sdim      }
1315218893Sdim    }
1316218893Sdim
1317218893Sdim    if (AllMethodsAreStatic)
1318218893Sdim      return true;
1319218893Sdim  }
1320218893Sdim
1321218893Sdim  return false;
1322218893Sdim}
1323218893Sdim
1324202379Srdivacky/// \brief Perform qualified name lookup into a given context.
1325193326Sed///
1326193326Sed/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1327193326Sed/// names when the context of those names is explicit specified, e.g.,
1328202379Srdivacky/// "std::vector" or "x->member", or as part of unqualified name lookup.
1329193326Sed///
1330193326Sed/// Different lookup criteria can find different names. For example, a
1331193326Sed/// particular scope can have both a struct and a function of the same
1332193326Sed/// name, and each can be found by certain lookup criteria. For more
1333193326Sed/// information about lookup criteria, see the documentation for the
1334193326Sed/// class LookupCriteria.
1335193326Sed///
1336202379Srdivacky/// \param R captures both the lookup criteria and any lookup results found.
1337202379Srdivacky///
1338202379Srdivacky/// \param LookupCtx The context in which qualified name lookup will
1339193326Sed/// search. If the lookup criteria permits, name lookup may also search
1340193326Sed/// in the parent contexts or (for C++ classes) base classes.
1341193326Sed///
1342218893Sdim/// \param InUnqualifiedLookup true if this is qualified name lookup that
1343202379Srdivacky/// occurs as part of unqualified name lookup.
1344193326Sed///
1345202379Srdivacky/// \returns true if lookup succeeded, false if it failed.
1346202379Srdivackybool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1347202379Srdivacky                               bool InUnqualifiedLookup) {
1348193326Sed  assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1349193326Sed
1350199482Srdivacky  if (!R.getLookupName())
1351198092Srdivacky    return false;
1352198092Srdivacky
1353198092Srdivacky  // Make sure that the declaration context is complete.
1354198092Srdivacky  assert((!isa<TagDecl>(LookupCtx) ||
1355198092Srdivacky          LookupCtx->isDependentContext() ||
1356226633Sdim          cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
1357198092Srdivacky          Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1358198092Srdivacky            ->isBeingDefined()) &&
1359198092Srdivacky         "Declaration context must already be complete!");
1360198092Srdivacky
1361193326Sed  // Perform qualified name lookup into the LookupCtx.
1362203955Srdivacky  if (LookupDirect(*this, R, LookupCtx)) {
1363198092Srdivacky    R.resolveKind();
1364202879Srdivacky    if (isa<CXXRecordDecl>(LookupCtx))
1365202879Srdivacky      R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1366198092Srdivacky    return true;
1367198092Srdivacky  }
1368193326Sed
1369198092Srdivacky  // Don't descend into implied contexts for redeclarations.
1370198092Srdivacky  // C++98 [namespace.qual]p6:
1371198092Srdivacky  //   In a declaration for a namespace member in which the
1372198092Srdivacky  //   declarator-id is a qualified-id, given that the qualified-id
1373198092Srdivacky  //   for the namespace member has the form
1374198092Srdivacky  //     nested-name-specifier unqualified-id
1375198092Srdivacky  //   the unqualified-id shall name a member of the namespace
1376198092Srdivacky  //   designated by the nested-name-specifier.
1377198092Srdivacky  // See also [class.mfct]p5 and [class.static.data]p2.
1378199482Srdivacky  if (R.isForRedeclaration())
1379198092Srdivacky    return false;
1380198092Srdivacky
1381199482Srdivacky  // If this is a namespace, look it up in the implied namespaces.
1382198092Srdivacky  if (LookupCtx->isFileContext())
1383203955Srdivacky    return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1384198092Srdivacky
1385198092Srdivacky  // If this isn't a C++ class, we aren't allowed to look into base
1386193326Sed  // classes, we're done.
1387202379Srdivacky  CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1388210299Sed  if (!LookupRec || !LookupRec->getDefinition())
1389198092Srdivacky    return false;
1390193326Sed
1391202379Srdivacky  // If we're performing qualified name lookup into a dependent class,
1392202379Srdivacky  // then we are actually looking into a current instantiation. If we have any
1393218893Sdim  // dependent base classes, then we either have to delay lookup until
1394202379Srdivacky  // template instantiation time (at which point all bases will be available)
1395202379Srdivacky  // or we have to fail.
1396202379Srdivacky  if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1397202379Srdivacky      LookupRec->hasAnyDependentBases()) {
1398202379Srdivacky    R.setNotFoundInCurrentInstantiation();
1399202379Srdivacky    return false;
1400202379Srdivacky  }
1401218893Sdim
1402193326Sed  // Perform lookup into our base classes.
1403198092Srdivacky  CXXBasePaths Paths;
1404198092Srdivacky  Paths.setOrigin(LookupRec);
1405193326Sed
1406193326Sed  // Look for this member in our base classes
1407198092Srdivacky  CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1408199482Srdivacky  switch (R.getLookupKind()) {
1409224145Sdim    case LookupObjCImplicitSelfParam:
1410198092Srdivacky    case LookupOrdinaryName:
1411198092Srdivacky    case LookupMemberName:
1412198092Srdivacky    case LookupRedeclarationWithLinkage:
1413198092Srdivacky      BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1414198092Srdivacky      break;
1415218893Sdim
1416198092Srdivacky    case LookupTagName:
1417198092Srdivacky      BaseCallback = &CXXRecordDecl::FindTagMember;
1418198092Srdivacky      break;
1419200583Srdivacky
1420212904Sdim    case LookupAnyName:
1421212904Sdim      BaseCallback = &LookupAnyMember;
1422212904Sdim      break;
1423218893Sdim
1424200583Srdivacky    case LookupUsingDeclName:
1425200583Srdivacky      // This lookup is for redeclarations only.
1426218893Sdim
1427198092Srdivacky    case LookupOperatorName:
1428198092Srdivacky    case LookupNamespaceName:
1429198092Srdivacky    case LookupObjCProtocolName:
1430218893Sdim    case LookupLabel:
1431198092Srdivacky      // These lookups will never find a member in a C++ class (or base class).
1432198092Srdivacky      return false;
1433218893Sdim
1434198092Srdivacky    case LookupNestedNameSpecifierName:
1435198092Srdivacky      BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1436198092Srdivacky      break;
1437198092Srdivacky  }
1438218893Sdim
1439199482Srdivacky  if (!LookupRec->lookupInBases(BaseCallback,
1440199482Srdivacky                                R.getLookupName().getAsOpaquePtr(), Paths))
1441198092Srdivacky    return false;
1442193326Sed
1443202879Srdivacky  R.setNamingClass(LookupRec);
1444202879Srdivacky
1445193326Sed  // C++ [class.member.lookup]p2:
1446193326Sed  //   [...] If the resulting set of declarations are not all from
1447193326Sed  //   sub-objects of the same type, or the set has a nonstatic member
1448193326Sed  //   and includes members from distinct sub-objects, there is an
1449193326Sed  //   ambiguity and the program is ill-formed. Otherwise that set is
1450193326Sed  //   the result of the lookup.
1451193326Sed  QualType SubobjectType;
1452193326Sed  int SubobjectNumber = 0;
1453205408Srdivacky  AccessSpecifier SubobjectAccess = AS_none;
1454218893Sdim
1455198092Srdivacky  for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1456193326Sed       Path != PathEnd; ++Path) {
1457198092Srdivacky    const CXXBasePathElement &PathElement = Path->back();
1458193326Sed
1459202879Srdivacky    // Pick the best (i.e. most permissive i.e. numerically lowest) access
1460202879Srdivacky    // across all paths.
1461202879Srdivacky    SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1462218893Sdim
1463193326Sed    // Determine whether we're looking at a distinct sub-object or not.
1464193326Sed    if (SubobjectType.isNull()) {
1465198092Srdivacky      // This is the first subobject we've looked at. Record its type.
1466193326Sed      SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1467193326Sed      SubobjectNumber = PathElement.SubobjectNumber;
1468218893Sdim      continue;
1469218893Sdim    }
1470218893Sdim
1471218893Sdim    if (SubobjectType
1472193326Sed                 != Context.getCanonicalType(PathElement.Base->getType())) {
1473193326Sed      // We found members of the given name in two subobjects of
1474218893Sdim      // different types. If the declaration sets aren't the same, this
1475218893Sdim      // this lookup is ambiguous.
1476218893Sdim      if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1477218893Sdim        CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1478218893Sdim        DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1479218893Sdim        DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1480218893Sdim
1481218893Sdim        while (FirstD != FirstPath->Decls.second &&
1482218893Sdim               CurrentD != Path->Decls.second) {
1483218893Sdim         if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1484218893Sdim             (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1485218893Sdim           break;
1486218893Sdim
1487218893Sdim          ++FirstD;
1488218893Sdim          ++CurrentD;
1489218893Sdim        }
1490218893Sdim
1491218893Sdim        if (FirstD == FirstPath->Decls.second &&
1492218893Sdim            CurrentD == Path->Decls.second)
1493218893Sdim          continue;
1494218893Sdim      }
1495218893Sdim
1496198092Srdivacky      R.setAmbiguousBaseSubobjectTypes(Paths);
1497198092Srdivacky      return true;
1498218893Sdim    }
1499218893Sdim
1500218893Sdim    if (SubobjectNumber != PathElement.SubobjectNumber) {
1501193326Sed      // We have a different subobject of the same type.
1502193326Sed
1503193326Sed      // C++ [class.member.lookup]p5:
1504193326Sed      //   A static member, a nested type or an enumerator defined in
1505193326Sed      //   a base class T can unambiguously be found even if an object
1506198092Srdivacky      //   has more than one base class subobject of type T.
1507218893Sdim      if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
1508193326Sed        continue;
1509193326Sed
1510193326Sed      // We have found a nonstatic member name in multiple, distinct
1511193326Sed      // subobjects. Name lookup is ambiguous.
1512198092Srdivacky      R.setAmbiguousBaseSubobjects(Paths);
1513198092Srdivacky      return true;
1514193326Sed    }
1515193326Sed  }
1516193326Sed
1517193326Sed  // Lookup in a base class succeeded; return these results.
1518193326Sed
1519198092Srdivacky  DeclContext::lookup_iterator I, E;
1520202879Srdivacky  for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1521202879Srdivacky    NamedDecl *D = *I;
1522202879Srdivacky    AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1523202879Srdivacky                                                    D->getAccess());
1524202879Srdivacky    R.addDecl(D, AS);
1525202879Srdivacky  }
1526198092Srdivacky  R.resolveKind();
1527198092Srdivacky  return true;
1528193326Sed}
1529193326Sed
1530193326Sed/// @brief Performs name lookup for a name that was parsed in the
1531193326Sed/// source code, and may contain a C++ scope specifier.
1532193326Sed///
1533193326Sed/// This routine is a convenience routine meant to be called from
1534193326Sed/// contexts that receive a name and an optional C++ scope specifier
1535193326Sed/// (e.g., "N::M::x"). It will then perform either qualified or
1536193326Sed/// unqualified name lookup (with LookupQualifiedName or LookupName,
1537193326Sed/// respectively) on the given name and return those results.
1538193326Sed///
1539193326Sed/// @param S        The scope from which unqualified name lookup will
1540193326Sed/// begin.
1541193326Sed///
1542198092Srdivacky/// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
1543198092Srdivacky///
1544198092Srdivacky/// @param EnteringContext Indicates whether we are going to enter the
1545198092Srdivacky/// context of the scope-specifier SS (if present).
1546198092Srdivacky///
1547198092Srdivacky/// @returns True if any decls were found (but possibly ambiguous)
1548207619Srdivackybool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1549199482Srdivacky                            bool AllowBuiltinCreation, bool EnteringContext) {
1550198092Srdivacky  if (SS && SS->isInvalid()) {
1551198092Srdivacky    // When the scope specifier is invalid, don't even look for
1552193326Sed    // anything.
1553198092Srdivacky    return false;
1554198092Srdivacky  }
1555193326Sed
1556198092Srdivacky  if (SS && SS->isSet()) {
1557198092Srdivacky    if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1558198092Srdivacky      // We have resolved the scope specifier to a particular declaration
1559198092Srdivacky      // contex, and will perform name lookup in that context.
1560207619Srdivacky      if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1561198092Srdivacky        return false;
1562193326Sed
1563199482Srdivacky      R.setContextRange(SS->getRange());
1564199482Srdivacky
1565199482Srdivacky      return LookupQualifiedName(R, DC);
1566193326Sed    }
1567193326Sed
1568198092Srdivacky    // We could not resolve the scope specified to a specific declaration
1569198092Srdivacky    // context, which means that SS refers to an unknown specialization.
1570198092Srdivacky    // Name lookup can't find anything in this case.
1571198092Srdivacky    return false;
1572193326Sed  }
1573193326Sed
1574198092Srdivacky  // Perform unqualified name lookup starting in the given scope.
1575199482Srdivacky  return LookupName(R, S, AllowBuiltinCreation);
1576193326Sed}
1577193326Sed
1578193326Sed
1579193326Sed/// @brief Produce a diagnostic describing the ambiguity that resulted
1580193326Sed/// from name lookup.
1581193326Sed///
1582193326Sed/// @param Result       The ambiguous name lookup result.
1583198092Srdivacky///
1584193326Sed/// @param Name         The name of the entity that name lookup was
1585193326Sed/// searching for.
1586193326Sed///
1587193326Sed/// @param NameLoc      The location of the name within the source code.
1588193326Sed///
1589193326Sed/// @param LookupRange  A source range that provides more
1590193326Sed/// source-location information concerning the lookup itself. For
1591193326Sed/// example, this range might highlight a nested-name-specifier that
1592193326Sed/// precedes the name.
1593193326Sed///
1594193326Sed/// @returns true
1595199482Srdivackybool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1596193326Sed  assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1597193326Sed
1598199482Srdivacky  DeclarationName Name = Result.getLookupName();
1599199482Srdivacky  SourceLocation NameLoc = Result.getNameLoc();
1600199482Srdivacky  SourceRange LookupRange = Result.getContextRange();
1601199482Srdivacky
1602198092Srdivacky  switch (Result.getAmbiguityKind()) {
1603198092Srdivacky  case LookupResult::AmbiguousBaseSubobjects: {
1604198092Srdivacky    CXXBasePaths *Paths = Result.getBasePaths();
1605198092Srdivacky    QualType SubobjectType = Paths->front().back().Base->getType();
1606198092Srdivacky    Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1607198092Srdivacky      << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1608198092Srdivacky      << LookupRange;
1609218893Sdim
1610198092Srdivacky    DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1611198092Srdivacky    while (isa<CXXMethodDecl>(*Found) &&
1612198092Srdivacky           cast<CXXMethodDecl>(*Found)->isStatic())
1613198092Srdivacky      ++Found;
1614218893Sdim
1615198092Srdivacky    Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1616218893Sdim
1617198092Srdivacky    return true;
1618198092Srdivacky  }
1619193326Sed
1620198092Srdivacky  case LookupResult::AmbiguousBaseSubobjectTypes: {
1621193326Sed    Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1622193326Sed      << Name << LookupRange;
1623218893Sdim
1624198092Srdivacky    CXXBasePaths *Paths = Result.getBasePaths();
1625193326Sed    std::set<Decl *> DeclsPrinted;
1626198092Srdivacky    for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1627198092Srdivacky                                      PathEnd = Paths->end();
1628193326Sed         Path != PathEnd; ++Path) {
1629193326Sed      Decl *D = *Path->Decls.first;
1630193326Sed      if (DeclsPrinted.insert(D).second)
1631193326Sed        Diag(D->getLocation(), diag::note_ambiguous_member_found);
1632193326Sed    }
1633193326Sed
1634193326Sed    return true;
1635198092Srdivacky  }
1636193326Sed
1637198092Srdivacky  case LookupResult::AmbiguousTagHiding: {
1638198092Srdivacky    Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1639193326Sed
1640198092Srdivacky    llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1641198092Srdivacky
1642198092Srdivacky    LookupResult::iterator DI, DE = Result.end();
1643198092Srdivacky    for (DI = Result.begin(); DI != DE; ++DI)
1644198092Srdivacky      if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1645198092Srdivacky        TagDecls.insert(TD);
1646198092Srdivacky        Diag(TD->getLocation(), diag::note_hidden_tag);
1647198092Srdivacky      }
1648198092Srdivacky
1649198092Srdivacky    for (DI = Result.begin(); DI != DE; ++DI)
1650198092Srdivacky      if (!isa<TagDecl>(*DI))
1651198092Srdivacky        Diag((*DI)->getLocation(), diag::note_hiding_object);
1652198092Srdivacky
1653198092Srdivacky    // For recovery purposes, go ahead and implement the hiding.
1654202879Srdivacky    LookupResult::Filter F = Result.makeFilter();
1655202879Srdivacky    while (F.hasNext()) {
1656202879Srdivacky      if (TagDecls.count(F.next()))
1657202879Srdivacky        F.erase();
1658202879Srdivacky    }
1659202879Srdivacky    F.done();
1660198092Srdivacky
1661198092Srdivacky    return true;
1662198092Srdivacky  }
1663198092Srdivacky
1664198092Srdivacky  case LookupResult::AmbiguousReference: {
1665198092Srdivacky    Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1666218893Sdim
1667198092Srdivacky    LookupResult::iterator DI = Result.begin(), DE = Result.end();
1668198092Srdivacky    for (; DI != DE; ++DI)
1669193326Sed      Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1670193326Sed
1671193326Sed    return true;
1672193326Sed  }
1673198092Srdivacky  }
1674193326Sed
1675200583Srdivacky  llvm_unreachable("unknown ambiguity kind");
1676193326Sed  return true;
1677193326Sed}
1678193326Sed
1679210299Sednamespace {
1680210299Sed  struct AssociatedLookup {
1681210299Sed    AssociatedLookup(Sema &S,
1682210299Sed                     Sema::AssociatedNamespaceSet &Namespaces,
1683210299Sed                     Sema::AssociatedClassSet &Classes)
1684210299Sed      : S(S), Namespaces(Namespaces), Classes(Classes) {
1685210299Sed    }
1686210299Sed
1687210299Sed    Sema &S;
1688210299Sed    Sema::AssociatedNamespaceSet &Namespaces;
1689210299Sed    Sema::AssociatedClassSet &Classes;
1690210299Sed  };
1691210299Sed}
1692210299Sed
1693198092Srdivackystatic void
1694210299SedaddAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1695198092Srdivacky
1696207619Srdivackystatic void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1697207619Srdivacky                                      DeclContext *Ctx) {
1698207619Srdivacky  // Add the associated namespace for this class.
1699207619Srdivacky
1700207619Srdivacky  // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1701207619Srdivacky  // be a locally scoped record.
1702207619Srdivacky
1703212904Sdim  // We skip out of inline namespaces. The innermost non-inline namespace
1704212904Sdim  // contains all names of all its nested inline namespaces anyway, so we can
1705212904Sdim  // replace the entire inline namespace tree with its root.
1706212904Sdim  while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1707212904Sdim         Ctx->isInlineNamespace())
1708207619Srdivacky    Ctx = Ctx->getParent();
1709207619Srdivacky
1710198092Srdivacky  if (Ctx->isFileContext())
1711207619Srdivacky    Namespaces.insert(Ctx->getPrimaryContext());
1712198092Srdivacky}
1713198092Srdivacky
1714198092Srdivacky// \brief Add the associated classes and namespaces for argument-dependent
1715198092Srdivacky// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1716198092Srdivackystatic void
1717210299SedaddAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1718210299Sed                                  const TemplateArgument &Arg) {
1719198092Srdivacky  // C++ [basic.lookup.koenig]p2, last bullet:
1720198092Srdivacky  //   -- [...] ;
1721198092Srdivacky  switch (Arg.getKind()) {
1722198092Srdivacky    case TemplateArgument::Null:
1723198092Srdivacky      break;
1724198092Srdivacky
1725198092Srdivacky    case TemplateArgument::Type:
1726198092Srdivacky      // [...] the namespaces and classes associated with the types of the
1727198092Srdivacky      // template arguments provided for template type parameters (excluding
1728198092Srdivacky      // template template parameters)
1729210299Sed      addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1730198092Srdivacky      break;
1731198092Srdivacky
1732218893Sdim    case TemplateArgument::Template:
1733218893Sdim    case TemplateArgument::TemplateExpansion: {
1734198092Srdivacky      // [...] the namespaces in which any template template arguments are
1735198092Srdivacky      // defined; and the classes in which any member templates used as
1736198092Srdivacky      // template template arguments are defined.
1737218893Sdim      TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
1738198092Srdivacky      if (ClassTemplateDecl *ClassTemplate
1739199482Srdivacky                 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1740198092Srdivacky        DeclContext *Ctx = ClassTemplate->getDeclContext();
1741198092Srdivacky        if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1742210299Sed          Result.Classes.insert(EnclosingClass);
1743198092Srdivacky        // Add the associated namespace for this class.
1744210299Sed        CollectEnclosingNamespace(Result.Namespaces, Ctx);
1745198092Srdivacky      }
1746198092Srdivacky      break;
1747199482Srdivacky    }
1748218893Sdim
1749199482Srdivacky    case TemplateArgument::Declaration:
1750198092Srdivacky    case TemplateArgument::Integral:
1751198092Srdivacky    case TemplateArgument::Expression:
1752198092Srdivacky      // [Note: non-type template arguments do not contribute to the set of
1753198092Srdivacky      //  associated namespaces. ]
1754198092Srdivacky      break;
1755198092Srdivacky
1756198092Srdivacky    case TemplateArgument::Pack:
1757198092Srdivacky      for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1758198092Srdivacky                                        PEnd = Arg.pack_end();
1759198092Srdivacky           P != PEnd; ++P)
1760210299Sed        addAssociatedClassesAndNamespaces(Result, *P);
1761198092Srdivacky      break;
1762198092Srdivacky  }
1763198092Srdivacky}
1764198092Srdivacky
1765193326Sed// \brief Add the associated classes and namespaces for
1766198092Srdivacky// argument-dependent lookup with an argument of class type
1767198092Srdivacky// (C++ [basic.lookup.koenig]p2).
1768198092Srdivackystatic void
1769210299SedaddAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1770210299Sed                                  CXXRecordDecl *Class) {
1771210299Sed
1772210299Sed  // Just silently ignore anything whose name is __va_list_tag.
1773210299Sed  if (Class->getDeclName() == Result.S.VAListTagName)
1774210299Sed    return;
1775210299Sed
1776193326Sed  // C++ [basic.lookup.koenig]p2:
1777193326Sed  //   [...]
1778193326Sed  //     -- If T is a class type (including unions), its associated
1779193326Sed  //        classes are: the class itself; the class of which it is a
1780193326Sed  //        member, if any; and its direct and indirect base
1781193326Sed  //        classes. Its associated namespaces are the namespaces in
1782198092Srdivacky  //        which its associated classes are defined.
1783193326Sed
1784193326Sed  // Add the class of which it is a member, if any.
1785193326Sed  DeclContext *Ctx = Class->getDeclContext();
1786193326Sed  if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1787210299Sed    Result.Classes.insert(EnclosingClass);
1788193326Sed  // Add the associated namespace for this class.
1789210299Sed  CollectEnclosingNamespace(Result.Namespaces, Ctx);
1790198092Srdivacky
1791193326Sed  // Add the class itself. If we've already seen this class, we don't
1792193326Sed  // need to visit base classes.
1793210299Sed  if (!Result.Classes.insert(Class))
1794193326Sed    return;
1795193326Sed
1796198092Srdivacky  // -- If T is a template-id, its associated namespaces and classes are
1797198092Srdivacky  //    the namespace in which the template is defined; for member
1798218893Sdim  //    templates, the member template's class; the namespaces and classes
1799198092Srdivacky  //    associated with the types of the template arguments provided for
1800198092Srdivacky  //    template type parameters (excluding template template parameters); the
1801198092Srdivacky  //    namespaces in which any template template arguments are defined; and
1802198092Srdivacky  //    the classes in which any member templates used as template template
1803198092Srdivacky  //    arguments are defined. [Note: non-type template arguments do not
1804198092Srdivacky  //    contribute to the set of associated namespaces. ]
1805198092Srdivacky  if (ClassTemplateSpecializationDecl *Spec
1806198092Srdivacky        = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1807198092Srdivacky    DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1808198092Srdivacky    if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1809210299Sed      Result.Classes.insert(EnclosingClass);
1810198092Srdivacky    // Add the associated namespace for this class.
1811210299Sed    CollectEnclosingNamespace(Result.Namespaces, Ctx);
1812193326Sed
1813198092Srdivacky    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1814198092Srdivacky    for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1815210299Sed      addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
1816198092Srdivacky  }
1817198092Srdivacky
1818203955Srdivacky  // Only recurse into base classes for complete types.
1819203955Srdivacky  if (!Class->hasDefinition()) {
1820203955Srdivacky    // FIXME: we might need to instantiate templates here
1821203955Srdivacky    return;
1822203955Srdivacky  }
1823203955Srdivacky
1824193326Sed  // Add direct and indirect base classes along with their associated
1825193326Sed  // namespaces.
1826226633Sdim  SmallVector<CXXRecordDecl *, 32> Bases;
1827193326Sed  Bases.push_back(Class);
1828193326Sed  while (!Bases.empty()) {
1829193326Sed    // Pop this class off the stack.
1830193326Sed    Class = Bases.back();
1831193326Sed    Bases.pop_back();
1832193326Sed
1833193326Sed    // Visit the base classes.
1834193326Sed    for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1835193326Sed                                         BaseEnd = Class->bases_end();
1836193326Sed         Base != BaseEnd; ++Base) {
1837198092Srdivacky      const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1838198893Srdivacky      // In dependent contexts, we do ADL twice, and the first time around,
1839198893Srdivacky      // the base type might be a dependent TemplateSpecializationType, or a
1840198893Srdivacky      // TemplateTypeParmType. If that happens, simply ignore it.
1841198893Srdivacky      // FIXME: If we want to support export, we probably need to add the
1842198893Srdivacky      // namespace of the template in a TemplateSpecializationType, or even
1843198893Srdivacky      // the classes and namespaces of known non-dependent arguments.
1844198893Srdivacky      if (!BaseType)
1845198893Srdivacky        continue;
1846193326Sed      CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1847210299Sed      if (Result.Classes.insert(BaseDecl)) {
1848193326Sed        // Find the associated namespace for this base class.
1849193326Sed        DeclContext *BaseCtx = BaseDecl->getDeclContext();
1850210299Sed        CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
1851193326Sed
1852193326Sed        // Make sure we visit the bases of this base class.
1853193326Sed        if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1854193326Sed          Bases.push_back(BaseDecl);
1855193326Sed      }
1856193326Sed    }
1857193326Sed  }
1858193326Sed}
1859193326Sed
1860193326Sed// \brief Add the associated classes and namespaces for
1861193326Sed// argument-dependent lookup with an argument of type T
1862198092Srdivacky// (C++ [basic.lookup.koenig]p2).
1863198092Srdivackystatic void
1864210299SedaddAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
1865193326Sed  // C++ [basic.lookup.koenig]p2:
1866193326Sed  //
1867193326Sed  //   For each argument type T in the function call, there is a set
1868193326Sed  //   of zero or more associated namespaces and a set of zero or more
1869193326Sed  //   associated classes to be considered. The sets of namespaces and
1870193326Sed  //   classes is determined entirely by the types of the function
1871193326Sed  //   arguments (and the namespace of any template template
1872193326Sed  //   argument). Typedef names and using-declarations used to specify
1873193326Sed  //   the types do not contribute to this set. The sets of namespaces
1874193326Sed  //   and classes are determined in the following way:
1875193326Sed
1876226633Sdim  SmallVector<const Type *, 16> Queue;
1877210299Sed  const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1878210299Sed
1879193326Sed  while (true) {
1880210299Sed    switch (T->getTypeClass()) {
1881210299Sed
1882210299Sed#define TYPE(Class, Base)
1883210299Sed#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1884210299Sed#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1885210299Sed#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1886210299Sed#define ABSTRACT_TYPE(Class, Base)
1887210299Sed#include "clang/AST/TypeNodes.def"
1888210299Sed      // T is canonical.  We can also ignore dependent types because
1889210299Sed      // we don't need to do ADL at the definition point, but if we
1890210299Sed      // wanted to implement template export (or if we find some other
1891210299Sed      // use for associated classes and namespaces...) this would be
1892210299Sed      // wrong.
1893193326Sed      break;
1894193326Sed
1895210299Sed    //    -- If T is a pointer to U or an array of U, its associated
1896210299Sed    //       namespaces and classes are those associated with U.
1897210299Sed    case Type::Pointer:
1898210299Sed      T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1899210299Sed      continue;
1900210299Sed    case Type::ConstantArray:
1901210299Sed    case Type::IncompleteArray:
1902210299Sed    case Type::VariableArray:
1903210299Sed      T = cast<ArrayType>(T)->getElementType().getTypePtr();
1904210299Sed      continue;
1905193326Sed
1906210299Sed    //     -- If T is a fundamental type, its associated sets of
1907210299Sed    //        namespaces and classes are both empty.
1908210299Sed    case Type::Builtin:
1909210299Sed      break;
1910210299Sed
1911210299Sed    //     -- If T is a class type (including unions), its associated
1912210299Sed    //        classes are: the class itself; the class of which it is a
1913210299Sed    //        member, if any; and its direct and indirect base
1914210299Sed    //        classes. Its associated namespaces are the namespaces in
1915210299Sed    //        which its associated classes are defined.
1916210299Sed    case Type::Record: {
1917210299Sed      CXXRecordDecl *Class
1918210299Sed        = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
1919210299Sed      addAssociatedClassesAndNamespaces(Result, Class);
1920210299Sed      break;
1921193326Sed    }
1922193326Sed
1923210299Sed    //     -- If T is an enumeration type, its associated namespace is
1924210299Sed    //        the namespace in which it is defined. If it is class
1925218893Sdim    //        member, its associated class is the member's class; else
1926210299Sed    //        it has no associated class.
1927210299Sed    case Type::Enum: {
1928210299Sed      EnumDecl *Enum = cast<EnumType>(T)->getDecl();
1929193326Sed
1930210299Sed      DeclContext *Ctx = Enum->getDeclContext();
1931210299Sed      if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1932210299Sed        Result.Classes.insert(EnclosingClass);
1933193326Sed
1934210299Sed      // Add the associated namespace for this class.
1935210299Sed      CollectEnclosingNamespace(Result.Namespaces, Ctx);
1936193326Sed
1937210299Sed      break;
1938210299Sed    }
1939193326Sed
1940210299Sed    //     -- If T is a function type, its associated namespaces and
1941210299Sed    //        classes are those associated with the function parameter
1942210299Sed    //        types and those associated with the return type.
1943210299Sed    case Type::FunctionProto: {
1944210299Sed      const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1945210299Sed      for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1946210299Sed                                             ArgEnd = Proto->arg_type_end();
1947210299Sed             Arg != ArgEnd; ++Arg)
1948210299Sed        Queue.push_back(Arg->getTypePtr());
1949210299Sed      // fallthrough
1950210299Sed    }
1951210299Sed    case Type::FunctionNoProto: {
1952210299Sed      const FunctionType *FnType = cast<FunctionType>(T);
1953210299Sed      T = FnType->getResultType().getTypePtr();
1954210299Sed      continue;
1955210299Sed    }
1956193326Sed
1957210299Sed    //     -- If T is a pointer to a member function of a class X, its
1958210299Sed    //        associated namespaces and classes are those associated
1959210299Sed    //        with the function parameter types and return type,
1960210299Sed    //        together with those associated with X.
1961210299Sed    //
1962210299Sed    //     -- If T is a pointer to a data member of class X, its
1963210299Sed    //        associated namespaces and classes are those associated
1964210299Sed    //        with the member type together with those associated with
1965210299Sed    //        X.
1966210299Sed    case Type::MemberPointer: {
1967210299Sed      const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1968193326Sed
1969210299Sed      // Queue up the class type into which this points.
1970210299Sed      Queue.push_back(MemberPtr->getClass());
1971198092Srdivacky
1972210299Sed      // And directly continue with the pointee type.
1973210299Sed      T = MemberPtr->getPointeeType().getTypePtr();
1974210299Sed      continue;
1975210299Sed    }
1976193326Sed
1977210299Sed    // As an extension, treat this like a normal pointer.
1978210299Sed    case Type::BlockPointer:
1979210299Sed      T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1980210299Sed      continue;
1981193326Sed
1982210299Sed    // References aren't covered by the standard, but that's such an
1983210299Sed    // obvious defect that we cover them anyway.
1984210299Sed    case Type::LValueReference:
1985210299Sed    case Type::RValueReference:
1986210299Sed      T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1987210299Sed      continue;
1988193326Sed
1989210299Sed    // These are fundamental types.
1990210299Sed    case Type::Vector:
1991210299Sed    case Type::ExtVector:
1992210299Sed    case Type::Complex:
1993210299Sed      break;
1994210299Sed
1995221345Sdim    // If T is an Objective-C object or interface type, or a pointer to an
1996221345Sdim    // object or interface type, the associated namespace is the global
1997221345Sdim    // namespace.
1998210299Sed    case Type::ObjCObject:
1999210299Sed    case Type::ObjCInterface:
2000210299Sed    case Type::ObjCObjectPointer:
2001221345Sdim      Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2002210299Sed      break;
2003226633Sdim
2004226633Sdim    // Atomic types are just wrappers; use the associations of the
2005226633Sdim    // contained type.
2006226633Sdim    case Type::Atomic:
2007226633Sdim      T = cast<AtomicType>(T)->getValueType().getTypePtr();
2008226633Sdim      continue;
2009210299Sed    }
2010210299Sed
2011210299Sed    if (Queue.empty()) break;
2012210299Sed    T = Queue.back();
2013210299Sed    Queue.pop_back();
2014193326Sed  }
2015193326Sed}
2016193326Sed
2017193326Sed/// \brief Find the associated classes and namespaces for
2018193326Sed/// argument-dependent lookup for a call with the given set of
2019193326Sed/// arguments.
2020193326Sed///
2021193326Sed/// This routine computes the sets of associated classes and associated
2022198092Srdivacky/// namespaces searched by argument-dependent lookup
2023193326Sed/// (C++ [basic.lookup.argdep]) for a given set of arguments.
2024198092Srdivackyvoid
2025193326SedSema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
2026193326Sed                                 AssociatedNamespaceSet &AssociatedNamespaces,
2027198092Srdivacky                                 AssociatedClassSet &AssociatedClasses) {
2028193326Sed  AssociatedNamespaces.clear();
2029193326Sed  AssociatedClasses.clear();
2030193326Sed
2031210299Sed  AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2032210299Sed
2033193326Sed  // C++ [basic.lookup.koenig]p2:
2034193326Sed  //   For each argument type T in the function call, there is a set
2035193326Sed  //   of zero or more associated namespaces and a set of zero or more
2036193326Sed  //   associated classes to be considered. The sets of namespaces and
2037193326Sed  //   classes is determined entirely by the types of the function
2038193326Sed  //   arguments (and the namespace of any template template
2039198092Srdivacky  //   argument).
2040193326Sed  for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2041193326Sed    Expr *Arg = Args[ArgIdx];
2042193326Sed
2043193326Sed    if (Arg->getType() != Context.OverloadTy) {
2044210299Sed      addAssociatedClassesAndNamespaces(Result, Arg->getType());
2045193326Sed      continue;
2046193326Sed    }
2047193326Sed
2048193326Sed    // [...] In addition, if the argument is the name or address of a
2049193326Sed    // set of overloaded functions and/or function templates, its
2050193326Sed    // associated classes and namespaces are the union of those
2051193326Sed    // associated with each of the members of the set: the namespace
2052193326Sed    // in which the function or function template is defined and the
2053193326Sed    // classes and namespaces associated with its (non-dependent)
2054193326Sed    // parameter types and return type.
2055198092Srdivacky    Arg = Arg->IgnoreParens();
2056199990Srdivacky    if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2057212904Sdim      if (unaryOp->getOpcode() == UO_AddrOf)
2058199990Srdivacky        Arg = unaryOp->getSubExpr();
2059193326Sed
2060210299Sed    UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2061210299Sed    if (!ULE) continue;
2062199990Srdivacky
2063210299Sed    for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2064210299Sed           I != E; ++I) {
2065201361Srdivacky      // Look through any using declarations to find the underlying function.
2066201361Srdivacky      NamedDecl *Fn = (*I)->getUnderlyingDecl();
2067201361Srdivacky
2068201361Srdivacky      FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2069195099Sed      if (!FDecl)
2070201361Srdivacky        FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
2071193326Sed
2072193326Sed      // Add the classes and namespaces associated with the parameter
2073193326Sed      // types and return type of this function.
2074210299Sed      addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2075193326Sed    }
2076193326Sed  }
2077193326Sed}
2078193326Sed
2079193326Sed/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2080193326Sed/// an acceptable non-member overloaded operator for a call whose
2081193326Sed/// arguments have types T1 (and, if non-empty, T2). This routine
2082193326Sed/// implements the check in C++ [over.match.oper]p3b2 concerning
2083193326Sed/// enumeration types.
2084198092Srdivackystatic bool
2085193326SedIsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2086193326Sed                                       QualType T1, QualType T2,
2087193326Sed                                       ASTContext &Context) {
2088193326Sed  if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2089193326Sed    return true;
2090193326Sed
2091193326Sed  if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2092193326Sed    return true;
2093193326Sed
2094198092Srdivacky  const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
2095193326Sed  if (Proto->getNumArgs() < 1)
2096193326Sed    return false;
2097193326Sed
2098193326Sed  if (T1->isEnumeralType()) {
2099193326Sed    QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2100199482Srdivacky    if (Context.hasSameUnqualifiedType(T1, ArgType))
2101193326Sed      return true;
2102193326Sed  }
2103193326Sed
2104193326Sed  if (Proto->getNumArgs() < 2)
2105193326Sed    return false;
2106193326Sed
2107193326Sed  if (!T2.isNull() && T2->isEnumeralType()) {
2108193326Sed    QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2109199482Srdivacky    if (Context.hasSameUnqualifiedType(T2, ArgType))
2110193326Sed      return true;
2111193326Sed  }
2112193326Sed
2113193326Sed  return false;
2114193326Sed}
2115193326Sed
2116199482SrdivackyNamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2117207619Srdivacky                                  SourceLocation Loc,
2118199482Srdivacky                                  LookupNameKind NameKind,
2119199482Srdivacky                                  RedeclarationKind Redecl) {
2120207619Srdivacky  LookupResult R(*this, Name, Loc, NameKind, Redecl);
2121199482Srdivacky  LookupName(R, S);
2122200583Srdivacky  return R.getAsSingle<NamedDecl>();
2123199482Srdivacky}
2124199482Srdivacky
2125193326Sed/// \brief Find the protocol with the given name, if any.
2126218893SdimObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2127207619Srdivacky                                       SourceLocation IdLoc) {
2128207619Srdivacky  Decl *D = LookupSingleName(TUScope, II, IdLoc,
2129207619Srdivacky                             LookupObjCProtocolName);
2130193326Sed  return cast_or_null<ObjCProtocolDecl>(D);
2131193326Sed}
2132193326Sed
2133193326Sedvoid Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2134198092Srdivacky                                        QualType T1, QualType T2,
2135203955Srdivacky                                        UnresolvedSetImpl &Functions) {
2136193326Sed  // C++ [over.match.oper]p3:
2137193326Sed  //     -- The set of non-member candidates is the result of the
2138193326Sed  //        unqualified lookup of operator@ in the context of the
2139193326Sed  //        expression according to the usual rules for name lookup in
2140193326Sed  //        unqualified function calls (3.4.2) except that all member
2141193326Sed  //        functions are ignored. However, if no operand has a class
2142193326Sed  //        type, only those non-member functions in the lookup set
2143198092Srdivacky  //        that have a first parameter of type T1 or "reference to
2144198092Srdivacky  //        (possibly cv-qualified) T1", when T1 is an enumeration
2145193326Sed  //        type, or (if there is a right operand) a second parameter
2146198092Srdivacky  //        of type T2 or "reference to (possibly cv-qualified) T2",
2147193326Sed  //        when T2 is an enumeration type, are candidate functions.
2148193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2149199482Srdivacky  LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2150199482Srdivacky  LookupName(Operators, S);
2151198092Srdivacky
2152193326Sed  assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2153193326Sed
2154198092Srdivacky  if (Operators.empty())
2155193326Sed    return;
2156193326Sed
2157193326Sed  for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2158193326Sed       Op != OpEnd; ++Op) {
2159207619Srdivacky    NamedDecl *Found = (*Op)->getUnderlyingDecl();
2160207619Srdivacky    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
2161193326Sed      if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2162207619Srdivacky        Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
2163198092Srdivacky    } else if (FunctionTemplateDecl *FunTmpl
2164207619Srdivacky                 = dyn_cast<FunctionTemplateDecl>(Found)) {
2165195341Sed      // FIXME: friend operators?
2166198092Srdivacky      // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2167195341Sed      // later?
2168195341Sed      if (!FunTmpl->getDeclContext()->isRecord())
2169207619Srdivacky        Functions.addDecl(*Op, Op.getAccess());
2170195341Sed    }
2171193326Sed  }
2172193326Sed}
2173193326Sed
2174224145SdimSema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
2175223017Sdim                                                            CXXSpecialMember SM,
2176223017Sdim                                                            bool ConstArg,
2177223017Sdim                                                            bool VolatileArg,
2178223017Sdim                                                            bool RValueThis,
2179223017Sdim                                                            bool ConstThis,
2180223017Sdim                                                            bool VolatileThis) {
2181224145Sdim  RD = RD->getDefinition();
2182224145Sdim  assert((RD && !RD->isBeingDefined()) &&
2183223017Sdim         "doing special member lookup into record that isn't fully complete");
2184223017Sdim  if (RValueThis || ConstThis || VolatileThis)
2185223017Sdim    assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2186223017Sdim           "constructors and destructors always have unqualified lvalue this");
2187223017Sdim  if (ConstArg || VolatileArg)
2188223017Sdim    assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2189223017Sdim           "parameter-less special members can't have qualified arguments");
2190223017Sdim
2191223017Sdim  llvm::FoldingSetNodeID ID;
2192224145Sdim  ID.AddPointer(RD);
2193223017Sdim  ID.AddInteger(SM);
2194223017Sdim  ID.AddInteger(ConstArg);
2195223017Sdim  ID.AddInteger(VolatileArg);
2196223017Sdim  ID.AddInteger(RValueThis);
2197223017Sdim  ID.AddInteger(ConstThis);
2198223017Sdim  ID.AddInteger(VolatileThis);
2199223017Sdim
2200223017Sdim  void *InsertPoint;
2201223017Sdim  SpecialMemberOverloadResult *Result =
2202223017Sdim    SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2203223017Sdim
2204223017Sdim  // This was already cached
2205223017Sdim  if (Result)
2206223017Sdim    return Result;
2207223017Sdim
2208223017Sdim  Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2209223017Sdim  Result = new (Result) SpecialMemberOverloadResult(ID);
2210223017Sdim  SpecialMemberCache.InsertNode(Result, InsertPoint);
2211223017Sdim
2212223017Sdim  if (SM == CXXDestructor) {
2213224145Sdim    if (!RD->hasDeclaredDestructor())
2214224145Sdim      DeclareImplicitDestructor(RD);
2215224145Sdim    CXXDestructorDecl *DD = RD->getDestructor();
2216223017Sdim    assert(DD && "record without a destructor");
2217223017Sdim    Result->setMethod(DD);
2218223017Sdim    Result->setSuccess(DD->isDeleted());
2219223017Sdim    Result->setConstParamMatch(false);
2220223017Sdim    return Result;
2221223017Sdim  }
2222223017Sdim
2223223017Sdim  // Prepare for overload resolution. Here we construct a synthetic argument
2224223017Sdim  // if necessary and make sure that implicit functions are declared.
2225224145Sdim  CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2226223017Sdim  DeclarationName Name;
2227223017Sdim  Expr *Arg = 0;
2228223017Sdim  unsigned NumArgs;
2229223017Sdim
2230223017Sdim  if (SM == CXXDefaultConstructor) {
2231223017Sdim    Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2232223017Sdim    NumArgs = 0;
2233224145Sdim    if (RD->needsImplicitDefaultConstructor())
2234224145Sdim      DeclareImplicitDefaultConstructor(RD);
2235223017Sdim  } else {
2236223017Sdim    if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2237223017Sdim      Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2238224145Sdim      if (!RD->hasDeclaredCopyConstructor())
2239224145Sdim        DeclareImplicitCopyConstructor(RD);
2240226633Sdim      if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2241226633Sdim        DeclareImplicitMoveConstructor(RD);
2242223017Sdim    } else {
2243223017Sdim      Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2244224145Sdim      if (!RD->hasDeclaredCopyAssignment())
2245224145Sdim        DeclareImplicitCopyAssignment(RD);
2246226633Sdim      if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2247226633Sdim        DeclareImplicitMoveAssignment(RD);
2248223017Sdim    }
2249223017Sdim
2250223017Sdim    QualType ArgType = CanTy;
2251223017Sdim    if (ConstArg)
2252223017Sdim      ArgType.addConst();
2253223017Sdim    if (VolatileArg)
2254223017Sdim      ArgType.addVolatile();
2255223017Sdim
2256223017Sdim    // This isn't /really/ specified by the standard, but it's implied
2257223017Sdim    // we should be working from an RValue in the case of move to ensure
2258223017Sdim    // that we prefer to bind to rvalue references, and an LValue in the
2259223017Sdim    // case of copy to ensure we don't bind to rvalue references.
2260223017Sdim    // Possibly an XValue is actually correct in the case of move, but
2261223017Sdim    // there is no semantic difference for class types in this restricted
2262223017Sdim    // case.
2263223017Sdim    ExprValueKind VK;
2264224145Sdim    if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2265223017Sdim      VK = VK_LValue;
2266223017Sdim    else
2267223017Sdim      VK = VK_RValue;
2268223017Sdim
2269223017Sdim    NumArgs = 1;
2270223017Sdim    Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2271223017Sdim  }
2272223017Sdim
2273223017Sdim  // Create the object argument
2274223017Sdim  QualType ThisTy = CanTy;
2275223017Sdim  if (ConstThis)
2276223017Sdim    ThisTy.addConst();
2277223017Sdim  if (VolatileThis)
2278223017Sdim    ThisTy.addVolatile();
2279224145Sdim  Expr::Classification Classification =
2280223017Sdim    (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2281223017Sdim                                   RValueThis ? VK_RValue : VK_LValue))->
2282223017Sdim        Classify(Context);
2283223017Sdim
2284223017Sdim  // Now we perform lookup on the name we computed earlier and do overload
2285223017Sdim  // resolution. Lookup is only performed directly into the class since there
2286223017Sdim  // will always be a (possibly implicit) declaration to shadow any others.
2287223017Sdim  OverloadCandidateSet OCS((SourceLocation()));
2288223017Sdim  DeclContext::lookup_iterator I, E;
2289223017Sdim  Result->setConstParamMatch(false);
2290223017Sdim
2291224145Sdim  llvm::tie(I, E) = RD->lookup(Name);
2292223017Sdim  assert((I != E) &&
2293223017Sdim         "lookup for a constructor or assignment operator was empty");
2294223017Sdim  for ( ; I != E; ++I) {
2295224145Sdim    Decl *Cand = *I;
2296224145Sdim
2297224145Sdim    if (Cand->isInvalidDecl())
2298223017Sdim      continue;
2299223017Sdim
2300224145Sdim    if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2301224145Sdim      // FIXME: [namespace.udecl]p15 says that we should only consider a
2302224145Sdim      // using declaration here if it does not match a declaration in the
2303224145Sdim      // derived class. We do not implement this correctly in other cases
2304224145Sdim      // either.
2305224145Sdim      Cand = U->getTargetDecl();
2306223017Sdim
2307224145Sdim      if (Cand->isInvalidDecl())
2308224145Sdim        continue;
2309224145Sdim    }
2310224145Sdim
2311224145Sdim    if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
2312224145Sdim      if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2313224145Sdim        AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
2314224145Sdim                           Classification, &Arg, NumArgs, OCS, true);
2315224145Sdim      else
2316224145Sdim        AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2317224145Sdim                             NumArgs, OCS, true);
2318224145Sdim
2319223017Sdim      // Here we're looking for a const parameter to speed up creation of
2320223017Sdim      // implicit copy methods.
2321223017Sdim      if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2322223017Sdim          (SM == CXXCopyConstructor &&
2323223017Sdim            cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2324223017Sdim        QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
2325224145Sdim        if (!ArgType->isReferenceType() ||
2326224145Sdim            ArgType->getPointeeType().isConstQualified())
2327223017Sdim          Result->setConstParamMatch(true);
2328223017Sdim      }
2329224145Sdim    } else if (FunctionTemplateDecl *Tmpl =
2330224145Sdim                 dyn_cast<FunctionTemplateDecl>(Cand)) {
2331224145Sdim      if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2332224145Sdim        AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2333224145Sdim                                   RD, 0, ThisTy, Classification, &Arg, NumArgs,
2334224145Sdim                                   OCS, true);
2335224145Sdim      else
2336224145Sdim        AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2337224145Sdim                                     0, &Arg, NumArgs, OCS, true);
2338223017Sdim    } else {
2339224145Sdim      assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
2340223017Sdim    }
2341223017Sdim  }
2342223017Sdim
2343223017Sdim  OverloadCandidateSet::iterator Best;
2344223017Sdim  switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2345223017Sdim    case OR_Success:
2346223017Sdim      Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2347223017Sdim      Result->setSuccess(true);
2348223017Sdim      break;
2349223017Sdim
2350223017Sdim    case OR_Deleted:
2351223017Sdim      Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2352223017Sdim      Result->setSuccess(false);
2353223017Sdim      break;
2354223017Sdim
2355223017Sdim    case OR_Ambiguous:
2356223017Sdim    case OR_No_Viable_Function:
2357223017Sdim      Result->setMethod(0);
2358223017Sdim      Result->setSuccess(false);
2359223017Sdim      break;
2360223017Sdim  }
2361223017Sdim
2362223017Sdim  return Result;
2363223017Sdim}
2364223017Sdim
2365223017Sdim/// \brief Look up the default constructor for the given class.
2366223017SdimCXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
2367223017Sdim  SpecialMemberOverloadResult *Result =
2368223017Sdim    LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2369223017Sdim                        false, false);
2370223017Sdim
2371223017Sdim  return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2372223017Sdim}
2373223017Sdim
2374224145Sdim/// \brief Look up the copying constructor for the given class.
2375224145SdimCXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2376224145Sdim                                                   unsigned Quals,
2377224145Sdim                                                   bool *ConstParamMatch) {
2378223017Sdim  assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2379223017Sdim         "non-const, non-volatile qualifiers for copy ctor arg");
2380223017Sdim  SpecialMemberOverloadResult *Result =
2381223017Sdim    LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2382223017Sdim                        Quals & Qualifiers::Volatile, false, false, false);
2383223017Sdim
2384223017Sdim  if (ConstParamMatch)
2385223017Sdim    *ConstParamMatch = Result->hasConstParamMatch();
2386223017Sdim
2387223017Sdim  return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2388223017Sdim}
2389223017Sdim
2390226633Sdim/// \brief Look up the moving constructor for the given class.
2391226633SdimCXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class) {
2392226633Sdim  SpecialMemberOverloadResult *Result =
2393226633Sdim    LookupSpecialMember(Class, CXXMoveConstructor, false,
2394226633Sdim                        false, false, false, false);
2395226633Sdim
2396226633Sdim  return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2397226633Sdim}
2398226633Sdim
2399210299Sed/// \brief Look up the constructors for the given class.
2400210299SedDeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2401223017Sdim  // If the implicit constructors have not yet been declared, do so now.
2402210299Sed  if (CanDeclareSpecialMemberFunction(Context, Class)) {
2403223017Sdim    if (Class->needsImplicitDefaultConstructor())
2404210299Sed      DeclareImplicitDefaultConstructor(Class);
2405210299Sed    if (!Class->hasDeclaredCopyConstructor())
2406210299Sed      DeclareImplicitCopyConstructor(Class);
2407226633Sdim    if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2408226633Sdim      DeclareImplicitMoveConstructor(Class);
2409210299Sed  }
2410218893Sdim
2411210299Sed  CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2412210299Sed  DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2413210299Sed  return Class->lookup(Name);
2414210299Sed}
2415210299Sed
2416224145Sdim/// \brief Look up the copying assignment operator for the given class.
2417224145SdimCXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2418224145Sdim                                             unsigned Quals, bool RValueThis,
2419224145Sdim                                             unsigned ThisQuals,
2420224145Sdim                                             bool *ConstParamMatch) {
2421224145Sdim  assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2422224145Sdim         "non-const, non-volatile qualifiers for copy assignment arg");
2423224145Sdim  assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2424224145Sdim         "non-const, non-volatile qualifiers for copy assignment this");
2425224145Sdim  SpecialMemberOverloadResult *Result =
2426224145Sdim    LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2427224145Sdim                        Quals & Qualifiers::Volatile, RValueThis,
2428224145Sdim                        ThisQuals & Qualifiers::Const,
2429224145Sdim                        ThisQuals & Qualifiers::Volatile);
2430224145Sdim
2431224145Sdim  if (ConstParamMatch)
2432224145Sdim    *ConstParamMatch = Result->hasConstParamMatch();
2433224145Sdim
2434224145Sdim  return Result->getMethod();
2435224145Sdim}
2436224145Sdim
2437226633Sdim/// \brief Look up the moving assignment operator for the given class.
2438226633SdimCXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2439226633Sdim                                            bool RValueThis,
2440226633Sdim                                            unsigned ThisQuals) {
2441226633Sdim  assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2442226633Sdim         "non-const, non-volatile qualifiers for copy assignment this");
2443226633Sdim  SpecialMemberOverloadResult *Result =
2444226633Sdim    LookupSpecialMember(Class, CXXMoveAssignment, false, false, RValueThis,
2445226633Sdim                        ThisQuals & Qualifiers::Const,
2446226633Sdim                        ThisQuals & Qualifiers::Volatile);
2447226633Sdim
2448226633Sdim  return Result->getMethod();
2449226633Sdim}
2450226633Sdim
2451210299Sed/// \brief Look for the destructor of the given class.
2452210299Sed///
2453218893Sdim/// During semantic analysis, this routine should be used in lieu of
2454210299Sed/// CXXRecordDecl::getDestructor().
2455210299Sed///
2456210299Sed/// \returns The destructor for this class.
2457210299SedCXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2458223017Sdim  return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2459223017Sdim                                                     false, false, false,
2460223017Sdim                                                     false, false)->getMethod());
2461210299Sed}
2462210299Sed
2463203955Srdivackyvoid ADLResult::insert(NamedDecl *New) {
2464203955Srdivacky  NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2465203955Srdivacky
2466203955Srdivacky  // If we haven't yet seen a decl for this key, or the last decl
2467203955Srdivacky  // was exactly this one, we're done.
2468203955Srdivacky  if (Old == 0 || Old == New) {
2469203955Srdivacky    Old = New;
2470203955Srdivacky    return;
2471203955Srdivacky  }
2472203955Srdivacky
2473203955Srdivacky  // Otherwise, decide which is a more recent redeclaration.
2474203955Srdivacky  FunctionDecl *OldFD, *NewFD;
2475203955Srdivacky  if (isa<FunctionTemplateDecl>(New)) {
2476203955Srdivacky    OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2477203955Srdivacky    NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2478203955Srdivacky  } else {
2479203955Srdivacky    OldFD = cast<FunctionDecl>(Old);
2480203955Srdivacky    NewFD = cast<FunctionDecl>(New);
2481203955Srdivacky  }
2482203955Srdivacky
2483203955Srdivacky  FunctionDecl *Cursor = NewFD;
2484203955Srdivacky  while (true) {
2485203955Srdivacky    Cursor = Cursor->getPreviousDeclaration();
2486203955Srdivacky
2487203955Srdivacky    // If we got to the end without finding OldFD, OldFD is the newer
2488203955Srdivacky    // declaration;  leave things as they are.
2489203955Srdivacky    if (!Cursor) return;
2490203955Srdivacky
2491203955Srdivacky    // If we do find OldFD, then NewFD is newer.
2492203955Srdivacky    if (Cursor == OldFD) break;
2493203955Srdivacky
2494203955Srdivacky    // Otherwise, keep looking.
2495203955Srdivacky  }
2496203955Srdivacky
2497203955Srdivacky  Old = New;
2498198092Srdivacky}
2499198092Srdivacky
2500198893Srdivackyvoid Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
2501193326Sed                                   Expr **Args, unsigned NumArgs,
2502221345Sdim                                   ADLResult &Result,
2503221345Sdim                                   bool StdNamespaceIsAssociated) {
2504193326Sed  // Find all of the associated namespaces and classes based on the
2505193326Sed  // arguments we have.
2506193326Sed  AssociatedNamespaceSet AssociatedNamespaces;
2507193326Sed  AssociatedClassSet AssociatedClasses;
2508198092Srdivacky  FindAssociatedClassesAndNamespaces(Args, NumArgs,
2509198092Srdivacky                                     AssociatedNamespaces,
2510198092Srdivacky                                     AssociatedClasses);
2511221345Sdim  if (StdNamespaceIsAssociated && StdNamespace)
2512221345Sdim    AssociatedNamespaces.insert(getStdNamespace());
2513193326Sed
2514198893Srdivacky  QualType T1, T2;
2515198893Srdivacky  if (Operator) {
2516198893Srdivacky    T1 = Args[0]->getType();
2517198893Srdivacky    if (NumArgs >= 2)
2518198893Srdivacky      T2 = Args[1]->getType();
2519198893Srdivacky  }
2520198893Srdivacky
2521193326Sed  // C++ [basic.lookup.argdep]p3:
2522193326Sed  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
2523193326Sed  //   and let Y be the lookup set produced by argument dependent
2524193326Sed  //   lookup (defined as follows). If X contains [...] then Y is
2525193326Sed  //   empty. Otherwise Y is the set of declarations found in the
2526193326Sed  //   namespaces associated with the argument types as described
2527193326Sed  //   below. The set of declarations found by the lookup of the name
2528193326Sed  //   is the union of X and Y.
2529193326Sed  //
2530193326Sed  // Here, we compute Y and add its members to the overloaded
2531193326Sed  // candidate set.
2532193326Sed  for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
2533198092Srdivacky                                     NSEnd = AssociatedNamespaces.end();
2534198092Srdivacky       NS != NSEnd; ++NS) {
2535193326Sed    //   When considering an associated namespace, the lookup is the
2536193326Sed    //   same as the lookup performed when the associated namespace is
2537193326Sed    //   used as a qualifier (3.4.3.2) except that:
2538193326Sed    //
2539193326Sed    //     -- Any using-directives in the associated namespace are
2540193326Sed    //        ignored.
2541193326Sed    //
2542198092Srdivacky    //     -- Any namespace-scope friend functions declared in
2543193326Sed    //        associated classes are visible within their respective
2544193326Sed    //        namespaces even if they are not visible during an ordinary
2545193326Sed    //        lookup (11.4).
2546193326Sed    DeclContext::lookup_iterator I, E;
2547195341Sed    for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
2548203955Srdivacky      NamedDecl *D = *I;
2549198092Srdivacky      // If the only declaration here is an ordinary friend, consider
2550198092Srdivacky      // it only if it was declared in an associated classes.
2551198092Srdivacky      if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
2552198092Srdivacky        DeclContext *LexDC = D->getLexicalDeclContext();
2553198092Srdivacky        if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2554198092Srdivacky          continue;
2555198092Srdivacky      }
2556198092Srdivacky
2557203955Srdivacky      if (isa<UsingShadowDecl>(D))
2558203955Srdivacky        D = cast<UsingShadowDecl>(D)->getTargetDecl();
2559203955Srdivacky
2560203955Srdivacky      if (isa<FunctionDecl>(D)) {
2561203955Srdivacky        if (Operator &&
2562203955Srdivacky            !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2563203955Srdivacky                                                    T1, T2, Context))
2564203955Srdivacky          continue;
2565203955Srdivacky      } else if (!isa<FunctionTemplateDecl>(D))
2566203955Srdivacky        continue;
2567203955Srdivacky
2568203955Srdivacky      Result.insert(D);
2569193326Sed    }
2570193326Sed  }
2571193326Sed}
2572201361Srdivacky
2573201361Srdivacky//----------------------------------------------------------------------------
2574201361Srdivacky// Search for all visible declarations.
2575201361Srdivacky//----------------------------------------------------------------------------
2576201361SrdivackyVisibleDeclConsumer::~VisibleDeclConsumer() { }
2577201361Srdivacky
2578201361Srdivackynamespace {
2579201361Srdivacky
2580201361Srdivackyclass ShadowContextRAII;
2581201361Srdivacky
2582201361Srdivackyclass VisibleDeclsRecord {
2583201361Srdivackypublic:
2584201361Srdivacky  /// \brief An entry in the shadow map, which is optimized to store a
2585201361Srdivacky  /// single declaration (the common case) but can also store a list
2586201361Srdivacky  /// of declarations.
2587226633Sdim  typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
2588218893Sdim
2589201361Srdivackyprivate:
2590201361Srdivacky  /// \brief A mapping from declaration names to the declarations that have
2591201361Srdivacky  /// this name within a particular scope.
2592201361Srdivacky  typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2593201361Srdivacky
2594201361Srdivacky  /// \brief A list of shadow maps, which is used to model name hiding.
2595201361Srdivacky  std::list<ShadowMap> ShadowMaps;
2596201361Srdivacky
2597201361Srdivacky  /// \brief The declaration contexts we have already visited.
2598201361Srdivacky  llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2599201361Srdivacky
2600201361Srdivacky  friend class ShadowContextRAII;
2601201361Srdivacky
2602201361Srdivackypublic:
2603201361Srdivacky  /// \brief Determine whether we have already visited this context
2604201361Srdivacky  /// (and, if not, note that we are going to visit that context now).
2605201361Srdivacky  bool visitedContext(DeclContext *Ctx) {
2606201361Srdivacky    return !VisitedContexts.insert(Ctx);
2607201361Srdivacky  }
2608201361Srdivacky
2609212904Sdim  bool alreadyVisitedContext(DeclContext *Ctx) {
2610212904Sdim    return VisitedContexts.count(Ctx);
2611212904Sdim  }
2612212904Sdim
2613201361Srdivacky  /// \brief Determine whether the given declaration is hidden in the
2614201361Srdivacky  /// current scope.
2615201361Srdivacky  ///
2616201361Srdivacky  /// \returns the declaration that hides the given declaration, or
2617201361Srdivacky  /// NULL if no such declaration exists.
2618201361Srdivacky  NamedDecl *checkHidden(NamedDecl *ND);
2619201361Srdivacky
2620201361Srdivacky  /// \brief Add a declaration to the current shadow map.
2621226633Sdim  void add(NamedDecl *ND) {
2622226633Sdim    ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2623226633Sdim  }
2624201361Srdivacky};
2625201361Srdivacky
2626201361Srdivacky/// \brief RAII object that records when we've entered a shadow context.
2627201361Srdivackyclass ShadowContextRAII {
2628201361Srdivacky  VisibleDeclsRecord &Visible;
2629201361Srdivacky
2630201361Srdivacky  typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2631201361Srdivacky
2632201361Srdivackypublic:
2633201361Srdivacky  ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2634201361Srdivacky    Visible.ShadowMaps.push_back(ShadowMap());
2635201361Srdivacky  }
2636201361Srdivacky
2637201361Srdivacky  ~ShadowContextRAII() {
2638201361Srdivacky    Visible.ShadowMaps.pop_back();
2639201361Srdivacky  }
2640201361Srdivacky};
2641201361Srdivacky
2642201361Srdivacky} // end anonymous namespace
2643201361Srdivacky
2644201361SrdivackyNamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2645202379Srdivacky  // Look through using declarations.
2646202379Srdivacky  ND = ND->getUnderlyingDecl();
2647218893Sdim
2648201361Srdivacky  unsigned IDNS = ND->getIdentifierNamespace();
2649201361Srdivacky  std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2650201361Srdivacky  for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2651201361Srdivacky       SM != SMEnd; ++SM) {
2652201361Srdivacky    ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2653201361Srdivacky    if (Pos == SM->end())
2654201361Srdivacky      continue;
2655201361Srdivacky
2656218893Sdim    for (ShadowMapEntry::iterator I = Pos->second.begin(),
2657201361Srdivacky                               IEnd = Pos->second.end();
2658201361Srdivacky         I != IEnd; ++I) {
2659201361Srdivacky      // A tag declaration does not hide a non-tag declaration.
2660207619Srdivacky      if ((*I)->hasTagIdentifierNamespace() &&
2661218893Sdim          (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2662201361Srdivacky                   Decl::IDNS_ObjCProtocol)))
2663201361Srdivacky        continue;
2664201361Srdivacky
2665201361Srdivacky      // Protocols are in distinct namespaces from everything else.
2666201361Srdivacky      if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2667201361Srdivacky           || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2668201361Srdivacky          (*I)->getIdentifierNamespace() != IDNS)
2669201361Srdivacky        continue;
2670201361Srdivacky
2671202379Srdivacky      // Functions and function templates in the same scope overload
2672202379Srdivacky      // rather than hide.  FIXME: Look for hiding based on function
2673202379Srdivacky      // signatures!
2674202379Srdivacky      if ((*I)->isFunctionOrFunctionTemplate() &&
2675202379Srdivacky          ND->isFunctionOrFunctionTemplate() &&
2676202379Srdivacky          SM == ShadowMaps.rbegin())
2677202379Srdivacky        continue;
2678218893Sdim
2679201361Srdivacky      // We've found a declaration that hides this one.
2680201361Srdivacky      return *I;
2681201361Srdivacky    }
2682201361Srdivacky  }
2683201361Srdivacky
2684201361Srdivacky  return 0;
2685201361Srdivacky}
2686201361Srdivacky
2687201361Srdivackystatic void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2688201361Srdivacky                               bool QualifiedNameLookup,
2689202379Srdivacky                               bool InBaseClass,
2690201361Srdivacky                               VisibleDeclConsumer &Consumer,
2691201361Srdivacky                               VisibleDeclsRecord &Visited) {
2692203955Srdivacky  if (!Ctx)
2693203955Srdivacky    return;
2694203955Srdivacky
2695201361Srdivacky  // Make sure we don't visit the same context twice.
2696201361Srdivacky  if (Visited.visitedContext(Ctx->getPrimaryContext()))
2697201361Srdivacky    return;
2698218893Sdim
2699210299Sed  if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2700210299Sed    Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2701210299Sed
2702201361Srdivacky  // Enumerate all of the results in this context.
2703218893Sdim  for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2704201361Srdivacky       CurCtx = CurCtx->getNextContext()) {
2705218893Sdim    for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2706201361Srdivacky                                 DEnd = CurCtx->decls_end();
2707201361Srdivacky         D != DEnd; ++D) {
2708218893Sdim      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
2709201361Srdivacky        if (Result.isAcceptableDecl(ND)) {
2710226633Sdim          Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
2711201361Srdivacky          Visited.add(ND);
2712201361Srdivacky        }
2713218893Sdim      } else if (ObjCForwardProtocolDecl *ForwardProto
2714218893Sdim                                      = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2715218893Sdim        for (ObjCForwardProtocolDecl::protocol_iterator
2716218893Sdim                  P = ForwardProto->protocol_begin(),
2717218893Sdim               PEnd = ForwardProto->protocol_end();
2718218893Sdim             P != PEnd;
2719218893Sdim             ++P) {
2720218893Sdim          if (Result.isAcceptableDecl(*P)) {
2721226633Sdim            Consumer.FoundDecl(*P, Visited.checkHidden(*P), Ctx, InBaseClass);
2722218893Sdim            Visited.add(*P);
2723218893Sdim          }
2724218893Sdim        }
2725218893Sdim      } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2726226633Sdim          ObjCInterfaceDecl *IFace = Class->getForwardInterfaceDecl();
2727218893Sdim          if (Result.isAcceptableDecl(IFace)) {
2728226633Sdim            Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), Ctx,
2729226633Sdim                               InBaseClass);
2730218893Sdim            Visited.add(IFace);
2731218893Sdim          }
2732218893Sdim      }
2733218893Sdim
2734212904Sdim      // Visit transparent contexts and inline namespaces inside this context.
2735201361Srdivacky      if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2736212904Sdim        if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
2737202379Srdivacky          LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
2738201361Srdivacky                             Consumer, Visited);
2739201361Srdivacky      }
2740201361Srdivacky    }
2741201361Srdivacky  }
2742201361Srdivacky
2743201361Srdivacky  // Traverse using directives for qualified name lookup.
2744201361Srdivacky  if (QualifiedNameLookup) {
2745201361Srdivacky    ShadowContextRAII Shadow(Visited);
2746201361Srdivacky    DeclContext::udir_iterator I, E;
2747201361Srdivacky    for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2748218893Sdim      LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
2749202379Srdivacky                         QualifiedNameLookup, InBaseClass, Consumer, Visited);
2750201361Srdivacky    }
2751201361Srdivacky  }
2752201361Srdivacky
2753202379Srdivacky  // Traverse the contexts of inherited C++ classes.
2754201361Srdivacky  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2755203955Srdivacky    if (!Record->hasDefinition())
2756203955Srdivacky      return;
2757203955Srdivacky
2758201361Srdivacky    for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2759201361Srdivacky                                         BEnd = Record->bases_end();
2760201361Srdivacky         B != BEnd; ++B) {
2761201361Srdivacky      QualType BaseType = B->getType();
2762218893Sdim
2763201361Srdivacky      // Don't look into dependent bases, because name lookup can't look
2764201361Srdivacky      // there anyway.
2765201361Srdivacky      if (BaseType->isDependentType())
2766201361Srdivacky        continue;
2767218893Sdim
2768201361Srdivacky      const RecordType *Record = BaseType->getAs<RecordType>();
2769201361Srdivacky      if (!Record)
2770201361Srdivacky        continue;
2771218893Sdim
2772201361Srdivacky      // FIXME: It would be nice to be able to determine whether referencing
2773201361Srdivacky      // a particular member would be ambiguous. For example, given
2774201361Srdivacky      //
2775201361Srdivacky      //   struct A { int member; };
2776201361Srdivacky      //   struct B { int member; };
2777201361Srdivacky      //   struct C : A, B { };
2778201361Srdivacky      //
2779201361Srdivacky      //   void f(C *c) { c->### }
2780201361Srdivacky      //
2781201361Srdivacky      // accessing 'member' would result in an ambiguity. However, we
2782201361Srdivacky      // could be smart enough to qualify the member with the base
2783201361Srdivacky      // class, e.g.,
2784201361Srdivacky      //
2785201361Srdivacky      //   c->B::member
2786201361Srdivacky      //
2787201361Srdivacky      // or
2788201361Srdivacky      //
2789201361Srdivacky      //   c->A::member
2790218893Sdim
2791201361Srdivacky      // Find results in this base class (and its bases).
2792201361Srdivacky      ShadowContextRAII Shadow(Visited);
2793201361Srdivacky      LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
2794202379Srdivacky                         true, Consumer, Visited);
2795202379Srdivacky    }
2796202379Srdivacky  }
2797218893Sdim
2798202379Srdivacky  // Traverse the contexts of Objective-C classes.
2799202379Srdivacky  if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2800202379Srdivacky    // Traverse categories.
2801202379Srdivacky    for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2802202379Srdivacky         Category; Category = Category->getNextClassCategory()) {
2803202379Srdivacky      ShadowContextRAII Shadow(Visited);
2804218893Sdim      LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2805201361Srdivacky                         Consumer, Visited);
2806201361Srdivacky    }
2807202379Srdivacky
2808202379Srdivacky    // Traverse protocols.
2809212904Sdim    for (ObjCInterfaceDecl::all_protocol_iterator
2810212904Sdim         I = IFace->all_referenced_protocol_begin(),
2811212904Sdim         E = IFace->all_referenced_protocol_end(); I != E; ++I) {
2812202379Srdivacky      ShadowContextRAII Shadow(Visited);
2813218893Sdim      LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2814202379Srdivacky                         Visited);
2815202379Srdivacky    }
2816202379Srdivacky
2817202379Srdivacky    // Traverse the superclass.
2818202379Srdivacky    if (IFace->getSuperClass()) {
2819202379Srdivacky      ShadowContextRAII Shadow(Visited);
2820202379Srdivacky      LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
2821202379Srdivacky                         true, Consumer, Visited);
2822202379Srdivacky    }
2823218893Sdim
2824207619Srdivacky    // If there is an implementation, traverse it. We do this to find
2825207619Srdivacky    // synthesized ivars.
2826207619Srdivacky    if (IFace->getImplementation()) {
2827207619Srdivacky      ShadowContextRAII Shadow(Visited);
2828218893Sdim      LookupVisibleDecls(IFace->getImplementation(), Result,
2829207619Srdivacky                         QualifiedNameLookup, true, Consumer, Visited);
2830207619Srdivacky    }
2831202379Srdivacky  } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2832202379Srdivacky    for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2833202379Srdivacky           E = Protocol->protocol_end(); I != E; ++I) {
2834202379Srdivacky      ShadowContextRAII Shadow(Visited);
2835218893Sdim      LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2836202379Srdivacky                         Visited);
2837202379Srdivacky    }
2838202379Srdivacky  } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2839202379Srdivacky    for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2840202379Srdivacky           E = Category->protocol_end(); I != E; ++I) {
2841202379Srdivacky      ShadowContextRAII Shadow(Visited);
2842218893Sdim      LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2843202379Srdivacky                         Visited);
2844202379Srdivacky    }
2845218893Sdim
2846207619Srdivacky    // If there is an implementation, traverse it.
2847207619Srdivacky    if (Category->getImplementation()) {
2848207619Srdivacky      ShadowContextRAII Shadow(Visited);
2849218893Sdim      LookupVisibleDecls(Category->getImplementation(), Result,
2850207619Srdivacky                         QualifiedNameLookup, true, Consumer, Visited);
2851218893Sdim    }
2852201361Srdivacky  }
2853201361Srdivacky}
2854201361Srdivacky
2855201361Srdivackystatic void LookupVisibleDecls(Scope *S, LookupResult &Result,
2856201361Srdivacky                               UnqualUsingDirectiveSet &UDirs,
2857201361Srdivacky                               VisibleDeclConsumer &Consumer,
2858201361Srdivacky                               VisibleDeclsRecord &Visited) {
2859201361Srdivacky  if (!S)
2860201361Srdivacky    return;
2861201361Srdivacky
2862218893Sdim  if (!S->getEntity() ||
2863218893Sdim      (!S->getParent() &&
2864212904Sdim       !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
2865202379Srdivacky      ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2866202379Srdivacky    // Walk through the declarations in this Scope.
2867202379Srdivacky    for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2868202379Srdivacky         D != DEnd; ++D) {
2869212904Sdim      if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2870202379Srdivacky        if (Result.isAcceptableDecl(ND)) {
2871226633Sdim          Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
2872202379Srdivacky          Visited.add(ND);
2873202379Srdivacky        }
2874202379Srdivacky    }
2875202379Srdivacky  }
2876218893Sdim
2877205219Srdivacky  // FIXME: C++ [temp.local]p8
2878201361Srdivacky  DeclContext *Entity = 0;
2879202379Srdivacky  if (S->getEntity()) {
2880201361Srdivacky    // Look into this scope's declaration context, along with any of its
2881201361Srdivacky    // parent lookup contexts (e.g., enclosing classes), up to the point
2882201361Srdivacky    // where we hit the context stored in the next outer scope.
2883201361Srdivacky    Entity = (DeclContext *)S->getEntity();
2884205219Srdivacky    DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
2885218893Sdim
2886205219Srdivacky    for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
2887201361Srdivacky         Ctx = Ctx->getLookupParent()) {
2888202379Srdivacky      if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2889202379Srdivacky        if (Method->isInstanceMethod()) {
2890202379Srdivacky          // For instance methods, look for ivars in the method's interface.
2891202379Srdivacky          LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2892202379Srdivacky                                  Result.getNameLoc(), Sema::LookupMemberName);
2893218893Sdim          if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
2894218893Sdim            LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2895226633Sdim                               /*InBaseClass=*/false, Consumer, Visited);
2896218893Sdim          }
2897202379Srdivacky        }
2898202379Srdivacky
2899202379Srdivacky        // We've already performed all of the name lookup that we need
2900202379Srdivacky        // to for Objective-C methods; the next context will be the
2901202379Srdivacky        // outer scope.
2902202379Srdivacky        break;
2903202379Srdivacky      }
2904202379Srdivacky
2905201361Srdivacky      if (Ctx->isFunctionOrMethod())
2906201361Srdivacky        continue;
2907218893Sdim
2908218893Sdim      LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
2909202379Srdivacky                         /*InBaseClass=*/false, Consumer, Visited);
2910201361Srdivacky    }
2911201361Srdivacky  } else if (!S->getParent()) {
2912201361Srdivacky    // Look into the translation unit scope. We walk through the translation
2913201361Srdivacky    // unit's declaration context, because the Scope itself won't have all of
2914201361Srdivacky    // the declarations if we loaded a precompiled header.
2915201361Srdivacky    // FIXME: We would like the translation unit's Scope object to point to the
2916201361Srdivacky    // translation unit, so we don't need this special "if" branch. However,
2917201361Srdivacky    // doing so would force the normal C++ name-lookup code to look into the
2918218893Sdim    // translation unit decl when the IdentifierInfo chains would suffice.
2919201361Srdivacky    // Once we fix that problem (which is part of a more general "don't look
2920202379Srdivacky    // in DeclContexts unless we have to" optimization), we can eliminate this.
2921201361Srdivacky    Entity = Result.getSema().Context.getTranslationUnitDecl();
2922218893Sdim    LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
2923202379Srdivacky                       /*InBaseClass=*/false, Consumer, Visited);
2924218893Sdim  }
2925218893Sdim
2926201361Srdivacky  if (Entity) {
2927201361Srdivacky    // Lookup visible declarations in any namespaces found by using
2928201361Srdivacky    // directives.
2929201361Srdivacky    UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2930201361Srdivacky    llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2931201361Srdivacky    for (; UI != UEnd; ++UI)
2932201361Srdivacky      LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
2933218893Sdim                         Result, /*QualifiedNameLookup=*/false,
2934202379Srdivacky                         /*InBaseClass=*/false, Consumer, Visited);
2935201361Srdivacky  }
2936201361Srdivacky
2937201361Srdivacky  // Lookup names in the parent scope.
2938201361Srdivacky  ShadowContextRAII Shadow(Visited);
2939201361Srdivacky  LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2940201361Srdivacky}
2941201361Srdivacky
2942201361Srdivackyvoid Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2943212904Sdim                              VisibleDeclConsumer &Consumer,
2944212904Sdim                              bool IncludeGlobalScope) {
2945201361Srdivacky  // Determine the set of using directives available during
2946201361Srdivacky  // unqualified name lookup.
2947201361Srdivacky  Scope *Initial = S;
2948201361Srdivacky  UnqualUsingDirectiveSet UDirs;
2949201361Srdivacky  if (getLangOptions().CPlusPlus) {
2950201361Srdivacky    // Find the first namespace or translation-unit scope.
2951201361Srdivacky    while (S && !isNamespaceOrTranslationUnitScope(S))
2952201361Srdivacky      S = S->getParent();
2953201361Srdivacky
2954201361Srdivacky    UDirs.visitScopeChain(Initial, S);
2955201361Srdivacky  }
2956201361Srdivacky  UDirs.done();
2957201361Srdivacky
2958201361Srdivacky  // Look for visible declarations.
2959201361Srdivacky  LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2960201361Srdivacky  VisibleDeclsRecord Visited;
2961212904Sdim  if (!IncludeGlobalScope)
2962212904Sdim    Visited.visitedContext(Context.getTranslationUnitDecl());
2963201361Srdivacky  ShadowContextRAII Shadow(Visited);
2964201361Srdivacky  ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2965201361Srdivacky}
2966201361Srdivacky
2967201361Srdivackyvoid Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2968212904Sdim                              VisibleDeclConsumer &Consumer,
2969212904Sdim                              bool IncludeGlobalScope) {
2970201361Srdivacky  LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2971201361Srdivacky  VisibleDeclsRecord Visited;
2972212904Sdim  if (!IncludeGlobalScope)
2973212904Sdim    Visited.visitedContext(Context.getTranslationUnitDecl());
2974201361Srdivacky  ShadowContextRAII Shadow(Visited);
2975218893Sdim  ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2976202379Srdivacky                       /*InBaseClass=*/false, Consumer, Visited);
2977201361Srdivacky}
2978201361Srdivacky
2979218893Sdim/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
2980221345Sdim/// If GnuLabelLoc is a valid source location, then this is a definition
2981221345Sdim/// of an __label__ label name, otherwise it is a normal label definition
2982221345Sdim/// or use.
2983218893SdimLabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
2984221345Sdim                                     SourceLocation GnuLabelLoc) {
2985218893Sdim  // Do a lookup to see if we have a label with this name already.
2986218893Sdim  NamedDecl *Res = 0;
2987221345Sdim
2988221345Sdim  if (GnuLabelLoc.isValid()) {
2989221345Sdim    // Local label definitions always shadow existing labels.
2990221345Sdim    Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
2991221345Sdim    Scope *S = CurScope;
2992221345Sdim    PushOnScopeChains(Res, S, true);
2993221345Sdim    return cast<LabelDecl>(Res);
2994221345Sdim  }
2995221345Sdim
2996221345Sdim  // Not a GNU local label.
2997221345Sdim  Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
2998221345Sdim  // If we found a label, check to see if it is in the same context as us.
2999221345Sdim  // When in a Block, we don't want to reuse a label in an enclosing function.
3000218893Sdim  if (Res && Res->getDeclContext() != CurContext)
3001218893Sdim    Res = 0;
3002218893Sdim  if (Res == 0) {
3003218893Sdim    // If not forward referenced or defined already, create the backing decl.
3004218893Sdim    Res = LabelDecl::Create(Context, CurContext, Loc, II);
3005221345Sdim    Scope *S = CurScope->getFnParent();
3006218893Sdim    assert(S && "Not in a function?");
3007218893Sdim    PushOnScopeChains(Res, S, true);
3008218893Sdim  }
3009218893Sdim  return cast<LabelDecl>(Res);
3010218893Sdim}
3011218893Sdim
3012218893Sdim//===----------------------------------------------------------------------===//
3013201361Srdivacky// Typo correction
3014218893Sdim//===----------------------------------------------------------------------===//
3015201361Srdivacky
3016201361Srdivackynamespace {
3017224145Sdim
3018224145Sdimtypedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
3019224145Sdimtypedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
3020224145Sdim
3021224145Sdimstatic const unsigned MaxTypoDistanceResultSets = 5;
3022224145Sdim
3023201361Srdivackyclass TypoCorrectionConsumer : public VisibleDeclConsumer {
3024201361Srdivacky  /// \brief The name written that is a typo in the source.
3025226633Sdim  StringRef Typo;
3026201361Srdivacky
3027201361Srdivacky  /// \brief The results found that have the smallest edit distance
3028201361Srdivacky  /// found (so far) with the typo name.
3029218893Sdim  ///
3030224145Sdim  /// The pointer value being set to the current DeclContext indicates
3031224145Sdim  /// whether there is a keyword with this name.
3032224145Sdim  TypoEditDistanceMap BestResults;
3033201361Srdivacky
3034224145Sdim  /// \brief The worst of the best N edit distances found so far.
3035224145Sdim  unsigned MaxEditDistance;
3036218893Sdim
3037224145Sdim  Sema &SemaRef;
3038224145Sdim
3039201361Srdivackypublic:
3040224145Sdim  explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
3041218893Sdim    : Typo(Typo->getName()),
3042224145Sdim      MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3043224145Sdim      SemaRef(SemaRef) { }
3044201361Srdivacky
3045224145Sdim  ~TypoCorrectionConsumer() {
3046224145Sdim    for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3047224145Sdim                                    IEnd = BestResults.end();
3048224145Sdim         I != IEnd;
3049224145Sdim         ++I)
3050224145Sdim      delete I->second;
3051224145Sdim  }
3052224145Sdim
3053226633Sdim  virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3054226633Sdim                         bool InBaseClass);
3055226633Sdim  void FoundName(StringRef Name);
3056226633Sdim  void addKeywordResult(StringRef Keyword);
3057226633Sdim  void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
3058226633Sdim               NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
3059224145Sdim  void addCorrection(TypoCorrection Correction);
3060201361Srdivacky
3061224145Sdim  typedef TypoResultsMap::iterator result_iterator;
3062224145Sdim  typedef TypoEditDistanceMap::iterator distance_iterator;
3063224145Sdim  distance_iterator begin() { return BestResults.begin(); }
3064224145Sdim  distance_iterator end()  { return BestResults.end(); }
3065224145Sdim  void erase(distance_iterator I) { BestResults.erase(I); }
3066218893Sdim  unsigned size() const { return BestResults.size(); }
3067218893Sdim  bool empty() const { return BestResults.empty(); }
3068201361Srdivacky
3069226633Sdim  TypoCorrection &operator[](StringRef Name) {
3070224145Sdim    return (*BestResults.begin()->second)[Name];
3071218893Sdim  }
3072218893Sdim
3073224145Sdim  unsigned getMaxEditDistance() const {
3074224145Sdim    return MaxEditDistance;
3075224145Sdim  }
3076224145Sdim
3077224145Sdim  unsigned getBestEditDistance() {
3078224145Sdim    return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3079224145Sdim  }
3080201361Srdivacky};
3081201361Srdivacky
3082201361Srdivacky}
3083201361Srdivacky
3084218893Sdimvoid TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
3085226633Sdim                                       DeclContext *Ctx, bool InBaseClass) {
3086201361Srdivacky  // Don't consider hidden names for typo correction.
3087201361Srdivacky  if (Hiding)
3088201361Srdivacky    return;
3089218893Sdim
3090201361Srdivacky  // Only consider entities with identifiers for names, ignoring
3091201361Srdivacky  // special names (constructors, overloaded operators, selectors,
3092201361Srdivacky  // etc.).
3093201361Srdivacky  IdentifierInfo *Name = ND->getIdentifier();
3094201361Srdivacky  if (!Name)
3095201361Srdivacky    return;
3096201361Srdivacky
3097218893Sdim  FoundName(Name->getName());
3098218893Sdim}
3099218893Sdim
3100226633Sdimvoid TypoCorrectionConsumer::FoundName(StringRef Name) {
3101218893Sdim  // Use a simple length-based heuristic to determine the minimum possible
3102218893Sdim  // edit distance. If the minimum isn't good enough, bail out early.
3103218893Sdim  unsigned MinED = abs((int)Name.size() - (int)Typo.size());
3104224145Sdim  if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
3105218893Sdim    return;
3106218893Sdim
3107218893Sdim  // Compute an upper bound on the allowable edit distance, so that the
3108218893Sdim  // edit-distance algorithm can short-circuit.
3109221345Sdim  unsigned UpperBound =
3110224145Sdim    std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
3111218893Sdim
3112201361Srdivacky  // Compute the edit distance between the typo and the name of this
3113201361Srdivacky  // entity. If this edit distance is not worse than the best edit
3114201361Srdivacky  // distance we've seen so far, add it to the list of results.
3115218893Sdim  unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3116218893Sdim
3117224145Sdim  if (ED > MaxEditDistance) {
3118218893Sdim    // This result is worse than the best results we've seen so far;
3119218893Sdim    // ignore it.
3120218893Sdim    return;
3121218893Sdim  }
3122201361Srdivacky
3123224145Sdim  addName(Name, NULL, ED);
3124201361Srdivacky}
3125201361Srdivacky
3126226633Sdimvoid TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3127207619Srdivacky  // Compute the edit distance between the typo and this keyword.
3128207619Srdivacky  // If this edit distance is not worse than the best edit
3129207619Srdivacky  // distance we've seen so far, add it to the list of results.
3130207619Srdivacky  unsigned ED = Typo.edit_distance(Keyword);
3131224145Sdim  if (ED > MaxEditDistance) {
3132218893Sdim    // This result is worse than the best results we've seen so far;
3133218893Sdim    // ignore it.
3134218893Sdim    return;
3135218893Sdim  }
3136218893Sdim
3137226633Sdim  addName(Keyword, NULL, ED, NULL, true);
3138207619Srdivacky}
3139207619Srdivacky
3140226633Sdimvoid TypoCorrectionConsumer::addName(StringRef Name,
3141224145Sdim                                     NamedDecl *ND,
3142224145Sdim                                     unsigned Distance,
3143226633Sdim                                     NestedNameSpecifier *NNS,
3144226633Sdim                                     bool isKeyword) {
3145226633Sdim  TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3146226633Sdim  if (isKeyword) TC.makeKeyword();
3147226633Sdim  addCorrection(TC);
3148224145Sdim}
3149224145Sdim
3150224145Sdimvoid TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3151226633Sdim  StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3152224145Sdim  TypoResultsMap *& Map = BestResults[Correction.getEditDistance()];
3153224145Sdim  if (!Map)
3154224145Sdim    Map = new TypoResultsMap;
3155224145Sdim
3156224145Sdim  TypoCorrection &CurrentCorrection = (*Map)[Name];
3157224145Sdim  if (!CurrentCorrection ||
3158224145Sdim      // FIXME: The following should be rolled up into an operator< on
3159224145Sdim      // TypoCorrection with a more principled definition.
3160224145Sdim      CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3161224145Sdim      Correction.getAsString(SemaRef.getLangOptions()) <
3162224145Sdim      CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3163224145Sdim    CurrentCorrection = Correction;
3164224145Sdim
3165224145Sdim  while (BestResults.size() > MaxTypoDistanceResultSets) {
3166224145Sdim    TypoEditDistanceMap::iterator Last = BestResults.end();
3167224145Sdim    --Last;
3168224145Sdim    delete Last->second;
3169224145Sdim    BestResults.erase(Last);
3170224145Sdim  }
3171224145Sdim}
3172224145Sdim
3173224145Sdimnamespace {
3174224145Sdim
3175224145Sdimclass SpecifierInfo {
3176224145Sdim public:
3177224145Sdim  DeclContext* DeclCtx;
3178224145Sdim  NestedNameSpecifier* NameSpecifier;
3179224145Sdim  unsigned EditDistance;
3180224145Sdim
3181224145Sdim  SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3182224145Sdim      : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3183224145Sdim};
3184224145Sdim
3185226633Sdimtypedef SmallVector<DeclContext*, 4> DeclContextList;
3186226633Sdimtypedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3187224145Sdim
3188224145Sdimclass NamespaceSpecifierSet {
3189224145Sdim  ASTContext &Context;
3190224145Sdim  DeclContextList CurContextChain;
3191224145Sdim  bool isSorted;
3192224145Sdim
3193224145Sdim  SpecifierInfoList Specifiers;
3194224145Sdim  llvm::SmallSetVector<unsigned, 4> Distances;
3195224145Sdim  llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3196224145Sdim
3197224145Sdim  /// \brief Helper for building the list of DeclContexts between the current
3198224145Sdim  /// context and the top of the translation unit
3199224145Sdim  static DeclContextList BuildContextChain(DeclContext *Start);
3200224145Sdim
3201224145Sdim  void SortNamespaces();
3202224145Sdim
3203224145Sdim public:
3204224145Sdim  explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
3205224145Sdim      : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3206224145Sdim        isSorted(true) {}
3207224145Sdim
3208224145Sdim  /// \brief Add the namespace to the set, computing the corresponding
3209224145Sdim  /// NestedNameSpecifier and its distance in the process.
3210224145Sdim  void AddNamespace(NamespaceDecl *ND);
3211224145Sdim
3212224145Sdim  typedef SpecifierInfoList::iterator iterator;
3213224145Sdim  iterator begin() {
3214224145Sdim    if (!isSorted) SortNamespaces();
3215224145Sdim    return Specifiers.begin();
3216224145Sdim  }
3217224145Sdim  iterator end() { return Specifiers.end(); }
3218224145Sdim};
3219224145Sdim
3220224145Sdim}
3221224145Sdim
3222224145SdimDeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
3223224145Sdim  assert(Start && "Bulding a context chain from a null context");
3224224145Sdim  DeclContextList Chain;
3225224145Sdim  for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3226224145Sdim       DC = DC->getLookupParent()) {
3227224145Sdim    NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3228224145Sdim    if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3229224145Sdim        !(ND && ND->isAnonymousNamespace()))
3230224145Sdim      Chain.push_back(DC->getPrimaryContext());
3231224145Sdim  }
3232224145Sdim  return Chain;
3233224145Sdim}
3234224145Sdim
3235224145Sdimvoid NamespaceSpecifierSet::SortNamespaces() {
3236226633Sdim  SmallVector<unsigned, 4> sortedDistances;
3237224145Sdim  sortedDistances.append(Distances.begin(), Distances.end());
3238224145Sdim
3239224145Sdim  if (sortedDistances.size() > 1)
3240224145Sdim    std::sort(sortedDistances.begin(), sortedDistances.end());
3241224145Sdim
3242224145Sdim  Specifiers.clear();
3243226633Sdim  for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
3244224145Sdim                                             DIEnd = sortedDistances.end();
3245224145Sdim       DI != DIEnd; ++DI) {
3246224145Sdim    SpecifierInfoList &SpecList = DistanceMap[*DI];
3247224145Sdim    Specifiers.append(SpecList.begin(), SpecList.end());
3248224145Sdim  }
3249224145Sdim
3250224145Sdim  isSorted = true;
3251224145Sdim}
3252224145Sdim
3253224145Sdimvoid NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
3254224145Sdim  DeclContext *Ctx = cast<DeclContext>(ND);
3255224145Sdim  NestedNameSpecifier *NNS = NULL;
3256224145Sdim  unsigned NumSpecifiers = 0;
3257224145Sdim  DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3258224145Sdim
3259224145Sdim  // Eliminate common elements from the two DeclContext chains
3260224145Sdim  for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3261224145Sdim                                      CEnd = CurContextChain.rend();
3262224145Sdim       C != CEnd && !NamespaceDeclChain.empty() &&
3263224145Sdim       NamespaceDeclChain.back() == *C; ++C) {
3264224145Sdim    NamespaceDeclChain.pop_back();
3265224145Sdim  }
3266224145Sdim
3267224145Sdim  // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3268224145Sdim  for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3269224145Sdim                                      CEnd = NamespaceDeclChain.rend();
3270224145Sdim       C != CEnd; ++C) {
3271224145Sdim    NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3272224145Sdim    if (ND) {
3273224145Sdim      NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3274224145Sdim      ++NumSpecifiers;
3275224145Sdim    }
3276224145Sdim  }
3277224145Sdim
3278224145Sdim  isSorted = false;
3279224145Sdim  Distances.insert(NumSpecifiers);
3280224145Sdim  DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3281224145Sdim}
3282224145Sdim
3283218893Sdim/// \brief Perform name lookup for a possible result for typo correction.
3284218893Sdimstatic void LookupPotentialTypoResult(Sema &SemaRef,
3285218893Sdim                                      LookupResult &Res,
3286218893Sdim                                      IdentifierInfo *Name,
3287218893Sdim                                      Scope *S, CXXScopeSpec *SS,
3288218893Sdim                                      DeclContext *MemberContext,
3289218893Sdim                                      bool EnteringContext,
3290218893Sdim                                      Sema::CorrectTypoContext CTC) {
3291218893Sdim  Res.suppressDiagnostics();
3292218893Sdim  Res.clear();
3293218893Sdim  Res.setLookupName(Name);
3294218893Sdim  if (MemberContext) {
3295218893Sdim    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3296218893Sdim      if (CTC == Sema::CTC_ObjCIvarLookup) {
3297218893Sdim        if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3298218893Sdim          Res.addDecl(Ivar);
3299218893Sdim          Res.resolveKind();
3300218893Sdim          return;
3301218893Sdim        }
3302218893Sdim      }
3303218893Sdim
3304218893Sdim      if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3305218893Sdim        Res.addDecl(Prop);
3306218893Sdim        Res.resolveKind();
3307218893Sdim        return;
3308218893Sdim      }
3309218893Sdim    }
3310218893Sdim
3311218893Sdim    SemaRef.LookupQualifiedName(Res, MemberContext);
3312218893Sdim    return;
3313218893Sdim  }
3314218893Sdim
3315218893Sdim  SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3316218893Sdim                           EnteringContext);
3317218893Sdim
3318218893Sdim  // Fake ivar lookup; this should really be part of
3319218893Sdim  // LookupParsedName.
3320218893Sdim  if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3321218893Sdim    if (Method->isInstanceMethod() && Method->getClassInterface() &&
3322218893Sdim        (Res.empty() ||
3323218893Sdim         (Res.isSingleResult() &&
3324218893Sdim          Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
3325218893Sdim       if (ObjCIvarDecl *IV
3326218893Sdim             = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3327218893Sdim         Res.addDecl(IV);
3328218893Sdim         Res.resolveKind();
3329218893Sdim       }
3330218893Sdim     }
3331218893Sdim  }
3332218893Sdim}
3333218893Sdim
3334224145Sdim/// \brief Add keywords to the consumer as possible typo corrections.
3335224145Sdimstatic void AddKeywordsToConsumer(Sema &SemaRef,
3336224145Sdim                                  TypoCorrectionConsumer &Consumer,
3337224145Sdim                                  Scope *S, Sema::CorrectTypoContext CTC) {
3338224145Sdim  // Add context-dependent keywords.
3339224145Sdim  bool WantTypeSpecifiers = false;
3340224145Sdim  bool WantExpressionKeywords = false;
3341224145Sdim  bool WantCXXNamedCasts = false;
3342224145Sdim  bool WantRemainingKeywords = false;
3343224145Sdim  switch (CTC) {
3344224145Sdim    case Sema::CTC_Unknown:
3345224145Sdim      WantTypeSpecifiers = true;
3346224145Sdim      WantExpressionKeywords = true;
3347224145Sdim      WantCXXNamedCasts = true;
3348224145Sdim      WantRemainingKeywords = true;
3349224145Sdim
3350224145Sdim      if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3351224145Sdim        if (Method->getClassInterface() &&
3352224145Sdim            Method->getClassInterface()->getSuperClass())
3353224145Sdim          Consumer.addKeywordResult("super");
3354224145Sdim
3355224145Sdim      break;
3356224145Sdim
3357224145Sdim    case Sema::CTC_NoKeywords:
3358224145Sdim      break;
3359224145Sdim
3360224145Sdim    case Sema::CTC_Type:
3361224145Sdim      WantTypeSpecifiers = true;
3362224145Sdim      break;
3363224145Sdim
3364224145Sdim    case Sema::CTC_ObjCMessageReceiver:
3365224145Sdim      Consumer.addKeywordResult("super");
3366224145Sdim      // Fall through to handle message receivers like expressions.
3367224145Sdim
3368224145Sdim    case Sema::CTC_Expression:
3369224145Sdim      if (SemaRef.getLangOptions().CPlusPlus)
3370224145Sdim        WantTypeSpecifiers = true;
3371224145Sdim      WantExpressionKeywords = true;
3372224145Sdim      // Fall through to get C++ named casts.
3373224145Sdim
3374224145Sdim    case Sema::CTC_CXXCasts:
3375224145Sdim      WantCXXNamedCasts = true;
3376224145Sdim      break;
3377224145Sdim
3378224145Sdim    case Sema::CTC_ObjCPropertyLookup:
3379224145Sdim      // FIXME: Add "isa"?
3380224145Sdim      break;
3381224145Sdim
3382224145Sdim    case Sema::CTC_MemberLookup:
3383224145Sdim      if (SemaRef.getLangOptions().CPlusPlus)
3384224145Sdim        Consumer.addKeywordResult("template");
3385224145Sdim      break;
3386224145Sdim
3387224145Sdim    case Sema::CTC_ObjCIvarLookup:
3388224145Sdim      break;
3389224145Sdim  }
3390224145Sdim
3391224145Sdim  if (WantTypeSpecifiers) {
3392224145Sdim    // Add type-specifier keywords to the set of results.
3393224145Sdim    const char *CTypeSpecs[] = {
3394224145Sdim      "char", "const", "double", "enum", "float", "int", "long", "short",
3395224145Sdim      "signed", "struct", "union", "unsigned", "void", "volatile",
3396224145Sdim      "_Complex", "_Imaginary",
3397224145Sdim      // storage-specifiers as well
3398224145Sdim      "extern", "inline", "static", "typedef"
3399224145Sdim    };
3400224145Sdim
3401224145Sdim    const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3402224145Sdim    for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3403224145Sdim      Consumer.addKeywordResult(CTypeSpecs[I]);
3404224145Sdim
3405224145Sdim    if (SemaRef.getLangOptions().C99)
3406224145Sdim      Consumer.addKeywordResult("restrict");
3407224145Sdim    if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3408224145Sdim      Consumer.addKeywordResult("bool");
3409224145Sdim    else if (SemaRef.getLangOptions().C99)
3410224145Sdim      Consumer.addKeywordResult("_Bool");
3411224145Sdim
3412224145Sdim    if (SemaRef.getLangOptions().CPlusPlus) {
3413224145Sdim      Consumer.addKeywordResult("class");
3414224145Sdim      Consumer.addKeywordResult("typename");
3415224145Sdim      Consumer.addKeywordResult("wchar_t");
3416224145Sdim
3417224145Sdim      if (SemaRef.getLangOptions().CPlusPlus0x) {
3418224145Sdim        Consumer.addKeywordResult("char16_t");
3419224145Sdim        Consumer.addKeywordResult("char32_t");
3420224145Sdim        Consumer.addKeywordResult("constexpr");
3421224145Sdim        Consumer.addKeywordResult("decltype");
3422224145Sdim        Consumer.addKeywordResult("thread_local");
3423224145Sdim      }
3424224145Sdim    }
3425224145Sdim
3426224145Sdim    if (SemaRef.getLangOptions().GNUMode)
3427224145Sdim      Consumer.addKeywordResult("typeof");
3428224145Sdim  }
3429224145Sdim
3430224145Sdim  if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3431224145Sdim    Consumer.addKeywordResult("const_cast");
3432224145Sdim    Consumer.addKeywordResult("dynamic_cast");
3433224145Sdim    Consumer.addKeywordResult("reinterpret_cast");
3434224145Sdim    Consumer.addKeywordResult("static_cast");
3435224145Sdim  }
3436224145Sdim
3437224145Sdim  if (WantExpressionKeywords) {
3438224145Sdim    Consumer.addKeywordResult("sizeof");
3439224145Sdim    if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3440224145Sdim      Consumer.addKeywordResult("false");
3441224145Sdim      Consumer.addKeywordResult("true");
3442224145Sdim    }
3443224145Sdim
3444224145Sdim    if (SemaRef.getLangOptions().CPlusPlus) {
3445224145Sdim      const char *CXXExprs[] = {
3446224145Sdim        "delete", "new", "operator", "throw", "typeid"
3447224145Sdim      };
3448224145Sdim      const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3449224145Sdim      for (unsigned I = 0; I != NumCXXExprs; ++I)
3450224145Sdim        Consumer.addKeywordResult(CXXExprs[I]);
3451224145Sdim
3452224145Sdim      if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3453224145Sdim          cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3454224145Sdim        Consumer.addKeywordResult("this");
3455224145Sdim
3456224145Sdim      if (SemaRef.getLangOptions().CPlusPlus0x) {
3457224145Sdim        Consumer.addKeywordResult("alignof");
3458224145Sdim        Consumer.addKeywordResult("nullptr");
3459224145Sdim      }
3460224145Sdim    }
3461224145Sdim  }
3462224145Sdim
3463224145Sdim  if (WantRemainingKeywords) {
3464224145Sdim    if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3465224145Sdim      // Statements.
3466224145Sdim      const char *CStmts[] = {
3467224145Sdim        "do", "else", "for", "goto", "if", "return", "switch", "while" };
3468224145Sdim      const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3469224145Sdim      for (unsigned I = 0; I != NumCStmts; ++I)
3470224145Sdim        Consumer.addKeywordResult(CStmts[I]);
3471224145Sdim
3472224145Sdim      if (SemaRef.getLangOptions().CPlusPlus) {
3473224145Sdim        Consumer.addKeywordResult("catch");
3474224145Sdim        Consumer.addKeywordResult("try");
3475224145Sdim      }
3476224145Sdim
3477224145Sdim      if (S && S->getBreakParent())
3478224145Sdim        Consumer.addKeywordResult("break");
3479224145Sdim
3480224145Sdim      if (S && S->getContinueParent())
3481224145Sdim        Consumer.addKeywordResult("continue");
3482224145Sdim
3483224145Sdim      if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3484224145Sdim        Consumer.addKeywordResult("case");
3485224145Sdim        Consumer.addKeywordResult("default");
3486224145Sdim      }
3487224145Sdim    } else {
3488224145Sdim      if (SemaRef.getLangOptions().CPlusPlus) {
3489224145Sdim        Consumer.addKeywordResult("namespace");
3490224145Sdim        Consumer.addKeywordResult("template");
3491224145Sdim      }
3492224145Sdim
3493224145Sdim      if (S && S->isClassScope()) {
3494224145Sdim        Consumer.addKeywordResult("explicit");
3495224145Sdim        Consumer.addKeywordResult("friend");
3496224145Sdim        Consumer.addKeywordResult("mutable");
3497224145Sdim        Consumer.addKeywordResult("private");
3498224145Sdim        Consumer.addKeywordResult("protected");
3499224145Sdim        Consumer.addKeywordResult("public");
3500224145Sdim        Consumer.addKeywordResult("virtual");
3501224145Sdim      }
3502224145Sdim    }
3503224145Sdim
3504224145Sdim    if (SemaRef.getLangOptions().CPlusPlus) {
3505224145Sdim      Consumer.addKeywordResult("using");
3506224145Sdim
3507224145Sdim      if (SemaRef.getLangOptions().CPlusPlus0x)
3508224145Sdim        Consumer.addKeywordResult("static_assert");
3509224145Sdim    }
3510224145Sdim  }
3511224145Sdim}
3512224145Sdim
3513201361Srdivacky/// \brief Try to "correct" a typo in the source code by finding
3514201361Srdivacky/// visible declarations whose names are similar to the name that was
3515201361Srdivacky/// present in the source code.
3516201361Srdivacky///
3517224145Sdim/// \param TypoName the \c DeclarationNameInfo structure that contains
3518224145Sdim/// the name that was present in the source code along with its location.
3519201361Srdivacky///
3520224145Sdim/// \param LookupKind the name-lookup criteria used to search for the name.
3521224145Sdim///
3522201361Srdivacky/// \param S the scope in which name lookup occurs.
3523201361Srdivacky///
3524201361Srdivacky/// \param SS the nested-name-specifier that precedes the name we're
3525201361Srdivacky/// looking for, if present.
3526201361Srdivacky///
3527201361Srdivacky/// \param MemberContext if non-NULL, the context in which to look for
3528201361Srdivacky/// a member access expression.
3529201361Srdivacky///
3530218893Sdim/// \param EnteringContext whether we're entering the context described by
3531201361Srdivacky/// the nested-name-specifier SS.
3532201361Srdivacky///
3533207619Srdivacky/// \param CTC The context in which typo correction occurs, which impacts the
3534207619Srdivacky/// set of keywords permitted.
3535207619Srdivacky///
3536202379Srdivacky/// \param OPT when non-NULL, the search for visible declarations will
3537202379Srdivacky/// also walk the protocols in the qualified interfaces of \p OPT.
3538202379Srdivacky///
3539224145Sdim/// \returns a \c TypoCorrection containing the corrected name if the typo
3540224145Sdim/// along with information such as the \c NamedDecl where the corrected name
3541224145Sdim/// was declared, and any additional \c NestedNameSpecifier needed to access
3542224145Sdim/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3543224145SdimTypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3544224145Sdim                                 Sema::LookupNameKind LookupKind,
3545224145Sdim                                 Scope *S, CXXScopeSpec *SS,
3546224145Sdim                                 DeclContext *MemberContext,
3547224145Sdim                                 bool EnteringContext,
3548224145Sdim                                 CorrectTypoContext CTC,
3549224145Sdim                                 const ObjCObjectPointerType *OPT) {
3550210299Sed  if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
3551224145Sdim    return TypoCorrection();
3552203955Srdivacky
3553201361Srdivacky  // We only attempt to correct typos for identifiers.
3554224145Sdim  IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
3555201361Srdivacky  if (!Typo)
3556224145Sdim    return TypoCorrection();
3557201361Srdivacky
3558201361Srdivacky  // If the scope specifier itself was invalid, don't try to correct
3559201361Srdivacky  // typos.
3560201361Srdivacky  if (SS && SS->isInvalid())
3561224145Sdim    return TypoCorrection();
3562201361Srdivacky
3563201361Srdivacky  // Never try to correct typos during template deduction or
3564201361Srdivacky  // instantiation.
3565201361Srdivacky  if (!ActiveTemplateInstantiations.empty())
3566224145Sdim    return TypoCorrection();
3567218893Sdim
3568224145Sdim  NamespaceSpecifierSet Namespaces(Context, CurContext);
3569218893Sdim
3570224145Sdim  TypoCorrectionConsumer Consumer(*this, Typo);
3571224145Sdim
3572207619Srdivacky  // Perform name lookup to find visible, similarly-named entities.
3573218893Sdim  bool IsUnqualifiedLookup = false;
3574202379Srdivacky  if (MemberContext) {
3575224145Sdim    LookupVisibleDecls(MemberContext, LookupKind, Consumer);
3576202379Srdivacky
3577202379Srdivacky    // Look in qualified interfaces.
3578202379Srdivacky    if (OPT) {
3579218893Sdim      for (ObjCObjectPointerType::qual_iterator
3580218893Sdim             I = OPT->qual_begin(), E = OPT->qual_end();
3581202379Srdivacky           I != E; ++I)
3582224145Sdim        LookupVisibleDecls(*I, LookupKind, Consumer);
3583202379Srdivacky    }
3584202379Srdivacky  } else if (SS && SS->isSet()) {
3585201361Srdivacky    DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3586201361Srdivacky    if (!DC)
3587224145Sdim      return TypoCorrection();
3588218893Sdim
3589218893Sdim    // Provide a stop gap for files that are just seriously broken.  Trying
3590218893Sdim    // to correct all typos can turn into a HUGE performance penalty, causing
3591218893Sdim    // some files to take minutes to get rejected by the parser.
3592218893Sdim    if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3593224145Sdim      return TypoCorrection();
3594218893Sdim    ++TyposCorrected;
3595218893Sdim
3596224145Sdim    LookupVisibleDecls(DC, LookupKind, Consumer);
3597201361Srdivacky  } else {
3598218893Sdim    IsUnqualifiedLookup = true;
3599218893Sdim    UnqualifiedTyposCorrectedMap::iterator Cached
3600218893Sdim      = UnqualifiedTyposCorrected.find(Typo);
3601218893Sdim    if (Cached == UnqualifiedTyposCorrected.end()) {
3602218893Sdim      // Provide a stop gap for files that are just seriously broken.  Trying
3603218893Sdim      // to correct all typos can turn into a HUGE performance penalty, causing
3604218893Sdim      // some files to take minutes to get rejected by the parser.
3605218893Sdim      if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3606224145Sdim        return TypoCorrection();
3607218893Sdim
3608218893Sdim      // For unqualified lookup, look through all of the names that we have
3609218893Sdim      // seen in this translation unit.
3610218893Sdim      for (IdentifierTable::iterator I = Context.Idents.begin(),
3611218893Sdim                                  IEnd = Context.Idents.end();
3612218893Sdim           I != IEnd; ++I)
3613218893Sdim        Consumer.FoundName(I->getKey());
3614218893Sdim
3615218893Sdim      // Walk through identifiers in external identifier sources.
3616218893Sdim      if (IdentifierInfoLookup *External
3617218893Sdim                              = Context.Idents.getExternalIdentifierLookup()) {
3618218893Sdim        llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
3619218893Sdim        do {
3620226633Sdim          StringRef Name = Iter->Next();
3621218893Sdim          if (Name.empty())
3622218893Sdim            break;
3623218893Sdim
3624218893Sdim          Consumer.FoundName(Name);
3625218893Sdim        } while (true);
3626218893Sdim      }
3627218893Sdim    } else {
3628218893Sdim      // Use the cached value, unless it's a keyword. In the keyword case, we'll
3629218893Sdim      // end up adding the keyword below.
3630224145Sdim      if (!Cached->second)
3631224145Sdim        return TypoCorrection();
3632218893Sdim
3633224145Sdim      if (!Cached->second.isKeyword())
3634224145Sdim        Consumer.addCorrection(Cached->second);
3635218893Sdim    }
3636201361Srdivacky  }
3637201361Srdivacky
3638224145Sdim  AddKeywordsToConsumer(*this, Consumer, S,  CTC);
3639218893Sdim
3640224145Sdim  // If we haven't found anything, we're done.
3641224145Sdim  if (Consumer.empty()) {
3642224145Sdim    // If this was an unqualified lookup, note that no correction was found.
3643224145Sdim    if (IsUnqualifiedLookup)
3644224145Sdim      (void)UnqualifiedTyposCorrected[Typo];
3645218893Sdim
3646224145Sdim    return TypoCorrection();
3647224145Sdim  }
3648218893Sdim
3649224145Sdim  // Make sure that the user typed at least 3 characters for each correction
3650224145Sdim  // made. Otherwise, we don't even both looking at the results.
3651224145Sdim  unsigned ED = Consumer.getBestEditDistance();
3652224145Sdim  if (ED > 0 && Typo->getName().size() / ED < 3) {
3653224145Sdim    // If this was an unqualified lookup, note that no correction was found.
3654224145Sdim    if (IsUnqualifiedLookup)
3655224145Sdim      (void)UnqualifiedTyposCorrected[Typo];
3656218893Sdim
3657224145Sdim    return TypoCorrection();
3658207619Srdivacky  }
3659207619Srdivacky
3660224145Sdim  // Build the NestedNameSpecifiers for the KnownNamespaces
3661224145Sdim  if (getLangOptions().CPlusPlus) {
3662224145Sdim    // Load any externally-known namespaces.
3663224145Sdim    if (ExternalSource && !LoadedExternalKnownNamespaces) {
3664226633Sdim      SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
3665224145Sdim      LoadedExternalKnownNamespaces = true;
3666224145Sdim      ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3667224145Sdim      for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3668224145Sdim        KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3669207619Srdivacky    }
3670224145Sdim
3671224145Sdim    for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3672224145Sdim           KNI = KnownNamespaces.begin(),
3673224145Sdim           KNIEnd = KnownNamespaces.end();
3674224145Sdim         KNI != KNIEnd; ++KNI)
3675224145Sdim      Namespaces.AddNamespace(KNI->first);
3676207619Srdivacky  }
3677218893Sdim
3678224145Sdim  // Weed out any names that could not be found by name lookup.
3679224145Sdim  llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3680224145Sdim  LookupResult TmpRes(*this, TypoName, LookupKind);
3681224145Sdim  TmpRes.suppressDiagnostics();
3682224145Sdim  while (!Consumer.empty()) {
3683224145Sdim    TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3684224145Sdim    unsigned ED = DI->first;
3685224145Sdim    for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3686224145Sdim                                              IEnd = DI->second->end();
3687224145Sdim         I != IEnd; /* Increment in loop. */) {
3688224145Sdim      // If the item already has been looked up or is a keyword, keep it
3689224145Sdim      if (I->second.isResolved()) {
3690224145Sdim        ++I;
3691224145Sdim        continue;
3692224145Sdim      }
3693218893Sdim
3694224145Sdim      // Perform name lookup on this name.
3695224145Sdim      IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3696224145Sdim      LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3697224145Sdim                                EnteringContext, CTC);
3698218893Sdim
3699224145Sdim      switch (TmpRes.getResultKind()) {
3700224145Sdim      case LookupResult::NotFound:
3701224145Sdim      case LookupResult::NotFoundInCurrentInstantiation:
3702226633Sdim      case LookupResult::FoundUnresolvedValue:
3703224145Sdim        QualifiedResults.insert(Name);
3704224145Sdim        // We didn't find this name in our scope, or didn't like what we found;
3705224145Sdim        // ignore it.
3706224145Sdim        {
3707224145Sdim          TypoCorrectionConsumer::result_iterator Next = I;
3708224145Sdim          ++Next;
3709224145Sdim          DI->second->erase(I);
3710224145Sdim          I = Next;
3711224145Sdim        }
3712224145Sdim        break;
3713218893Sdim
3714224145Sdim      case LookupResult::Ambiguous:
3715224145Sdim        // We don't deal with ambiguities.
3716224145Sdim        return TypoCorrection();
3717218893Sdim
3718226633Sdim      case LookupResult::FoundOverloaded: {
3719226633Sdim        // Store all of the Decls for overloaded symbols
3720226633Sdim        for (LookupResult::iterator TRD = TmpRes.begin(),
3721226633Sdim                                 TRDEnd = TmpRes.end();
3722226633Sdim             TRD != TRDEnd; ++TRD)
3723226633Sdim          I->second.addCorrectionDecl(*TRD);
3724226633Sdim        ++I;
3725226633Sdim        break;
3726226633Sdim      }
3727226633Sdim
3728224145Sdim      case LookupResult::Found:
3729224145Sdim        I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3730224145Sdim        ++I;
3731224145Sdim        break;
3732207619Srdivacky      }
3733207619Srdivacky    }
3734218893Sdim
3735224145Sdim    if (DI->second->empty())
3736224145Sdim      Consumer.erase(DI);
3737224145Sdim    else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3738224145Sdim      // If there are results in the closest possible bucket, stop
3739224145Sdim      break;
3740218893Sdim
3741224145Sdim    // Only perform the qualified lookups for C++
3742224145Sdim    if (getLangOptions().CPlusPlus) {
3743224145Sdim      TmpRes.suppressDiagnostics();
3744224145Sdim      for (llvm::SmallPtrSet<IdentifierInfo*,
3745224145Sdim                             16>::iterator QRI = QualifiedResults.begin(),
3746224145Sdim                                        QRIEnd = QualifiedResults.end();
3747224145Sdim           QRI != QRIEnd; ++QRI) {
3748224145Sdim        for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3749224145Sdim                                          NIEnd = Namespaces.end();
3750224145Sdim             NI != NIEnd; ++NI) {
3751224145Sdim          DeclContext *Ctx = NI->DeclCtx;
3752224145Sdim          unsigned QualifiedED = ED + NI->EditDistance;
3753218893Sdim
3754224145Sdim          // Stop searching once the namespaces are too far away to create
3755224145Sdim          // acceptable corrections for this identifier (since the namespaces
3756224145Sdim          // are sorted in ascending order by edit distance)
3757224145Sdim          if (QualifiedED > Consumer.getMaxEditDistance()) break;
3758218893Sdim
3759224145Sdim          TmpRes.clear();
3760224145Sdim          TmpRes.setLookupName(*QRI);
3761224145Sdim          if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3762218893Sdim
3763224145Sdim          switch (TmpRes.getResultKind()) {
3764224145Sdim          case LookupResult::Found:
3765224145Sdim            Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3766224145Sdim                             QualifiedED, NI->NameSpecifier);
3767224145Sdim            break;
3768226633Sdim          case LookupResult::FoundOverloaded: {
3769226633Sdim            TypoCorrection corr(&Context.Idents.get((*QRI)->getName()), NULL,
3770226633Sdim                                NI->NameSpecifier, QualifiedED);
3771226633Sdim            for (LookupResult::iterator TRD = TmpRes.begin(),
3772226633Sdim                                     TRDEnd = TmpRes.end();
3773226633Sdim                 TRD != TRDEnd; ++TRD)
3774226633Sdim              corr.addCorrectionDecl(*TRD);
3775226633Sdim            Consumer.addCorrection(corr);
3776226633Sdim            break;
3777226633Sdim          }
3778224145Sdim          case LookupResult::NotFound:
3779224145Sdim          case LookupResult::NotFoundInCurrentInstantiation:
3780224145Sdim          case LookupResult::Ambiguous:
3781226633Sdim          case LookupResult::FoundUnresolvedValue:
3782224145Sdim            break;
3783224145Sdim          }
3784224145Sdim        }
3785207619Srdivacky      }
3786207619Srdivacky    }
3787218893Sdim
3788224145Sdim    QualifiedResults.clear();
3789207619Srdivacky  }
3790218893Sdim
3791224145Sdim  // No corrections remain...
3792224145Sdim  if (Consumer.empty()) return TypoCorrection();
3793218893Sdim
3794224145Sdim  TypoResultsMap &BestResults = *Consumer.begin()->second;
3795224145Sdim  ED = Consumer.begin()->first;
3796201361Srdivacky
3797218893Sdim  if (ED > 0 && Typo->getName().size() / ED < 3) {
3798218893Sdim    // If this was an unqualified lookup, note that no correction was found.
3799218893Sdim    if (IsUnqualifiedLookup)
3800218893Sdim      (void)UnqualifiedTyposCorrected[Typo];
3801218893Sdim
3802224145Sdim    return TypoCorrection();
3803218893Sdim  }
3804218893Sdim
3805224145Sdim  // If we have multiple possible corrections, eliminate the ones where we
3806224145Sdim  // added namespace qualifiers to try to resolve the ambiguity (and to favor
3807224145Sdim  // corrections without additional namespace qualifiers)
3808224145Sdim  if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3809224145Sdim    TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3810224145Sdim    for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3811224145Sdim                                              IEnd = DI->second->end();
3812224145Sdim         I != IEnd; /* Increment in loop. */) {
3813224145Sdim      if (I->second.getCorrectionSpecifier() != NULL) {
3814224145Sdim        TypoCorrectionConsumer::result_iterator Cur = I;
3815224145Sdim        ++I;
3816224145Sdim        DI->second->erase(Cur);
3817224145Sdim      } else ++I;
3818218893Sdim    }
3819207619Srdivacky  }
3820202379Srdivacky
3821218893Sdim  // If only a single name remains, return that result.
3822224145Sdim  if (BestResults.size() == 1) {
3823224145Sdim    const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3824224145Sdim    const TypoCorrection &Result = Correction.second;
3825218893Sdim
3826224145Sdim    // Don't correct to a keyword that's the same as the typo; the keyword
3827224145Sdim    // wasn't actually in scope.
3828224145Sdim    if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3829218893Sdim
3830218893Sdim    // Record the correction for unqualified lookup.
3831218893Sdim    if (IsUnqualifiedLookup)
3832224145Sdim      UnqualifiedTyposCorrected[Typo] = Result;
3833218893Sdim
3834224145Sdim    return Result;
3835201361Srdivacky  }
3836224145Sdim  else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3837224145Sdim           && BestResults["super"].isKeyword()) {
3838224145Sdim    // Prefer 'super' when we're completing in a message-receiver
3839218893Sdim    // context.
3840201361Srdivacky
3841218893Sdim    // Don't correct to a keyword that's the same as the typo; the keyword
3842218893Sdim    // wasn't actually in scope.
3843224145Sdim    if (ED == 0) return TypoCorrection();
3844202379Srdivacky
3845218893Sdim    // Record the correction for unqualified lookup.
3846218893Sdim    if (IsUnqualifiedLookup)
3847224145Sdim      UnqualifiedTyposCorrected[Typo] = BestResults["super"];
3848201361Srdivacky
3849224145Sdim    return BestResults["super"];
3850201361Srdivacky  }
3851201361Srdivacky
3852218893Sdim  if (IsUnqualifiedLookup)
3853218893Sdim    (void)UnqualifiedTyposCorrected[Typo];
3854218893Sdim
3855224145Sdim  return TypoCorrection();
3856201361Srdivacky}
3857224145Sdim
3858226633Sdimvoid TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
3859226633Sdim  if (!CDecl) return;
3860226633Sdim
3861226633Sdim  if (isKeyword())
3862226633Sdim    CorrectionDecls.clear();
3863226633Sdim
3864226633Sdim  CorrectionDecls.push_back(CDecl);
3865226633Sdim
3866226633Sdim  if (!CorrectionName)
3867226633Sdim    CorrectionName = CDecl->getDeclName();
3868226633Sdim}
3869226633Sdim
3870224145Sdimstd::string TypoCorrection::getAsString(const LangOptions &LO) const {
3871224145Sdim  if (CorrectionNameSpec) {
3872224145Sdim    std::string tmpBuffer;
3873224145Sdim    llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3874224145Sdim    CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3875224145Sdim    return PrefixOStream.str() + CorrectionName.getAsString();
3876224145Sdim  }
3877224145Sdim
3878224145Sdim  return CorrectionName.getAsString();
3879224145Sdim}
3880