Coverage Report

Created: 2021-08-24 07:12

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