Coverage Report

Created: 2021-01-23 06:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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 semantic analysis for declarations.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTLambda.h"
17
#include "clang/AST/CXXInheritance.h"
18
#include "clang/AST/CharUnits.h"
19
#include "clang/AST/CommentDiagnostic.h"
20
#include "clang/AST/DeclCXX.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/EvaluatedExprVisitor.h"
24
#include "clang/AST/Expr.h"
25
#include "clang/AST/ExprCXX.h"
26
#include "clang/AST/NonTrivialTypeVisitor.h"
27
#include "clang/AST/StmtCXX.h"
28
#include "clang/Basic/Builtins.h"
29
#include "clang/Basic/PartialDiagnostic.h"
30
#include "clang/Basic/SourceManager.h"
31
#include "clang/Basic/TargetInfo.h"
32
#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33
#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34
#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35
#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36
#include "clang/Sema/CXXFieldCollector.h"
37
#include "clang/Sema/DeclSpec.h"
38
#include "clang/Sema/DelayedDiagnostic.h"
39
#include "clang/Sema/Initialization.h"
40
#include "clang/Sema/Lookup.h"
41
#include "clang/Sema/ParsedTemplate.h"
42
#include "clang/Sema/Scope.h"
43
#include "clang/Sema/ScopeInfo.h"
44
#include "clang/Sema/SemaInternal.h"
45
#include "clang/Sema/Template.h"
46
#include "llvm/ADT/SmallString.h"
47
#include "llvm/ADT/Triple.h"
48
#include <algorithm>
49
#include <cstring>
50
#include <functional>
51
#include <unordered_map>
52
53
using namespace clang;
54
using namespace sema;
55
56
4.79M
Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57
4.79M
  if (OwnedType) {
58
1.71k
    Decl *Group[2] = { OwnedType, Ptr };
59
1.71k
    return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60
1.71k
  }
61
62
4.78M
  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63
4.78M
}
64
65
namespace {
66
67
class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68
 public:
69
   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70
                        bool AllowTemplates = false,
71
                        bool AllowNonTemplates = true)
72
       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73
1.24k
         AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74
1.24k
     WantExpressionKeywords = false;
75
1.24k
     WantCXXNamedCasts = false;
76
1.24k
     WantRemainingKeywords = false;
77
1.24k
  }
78
79
803
  bool ValidateCandidate(const TypoCorrection &candidate) override {
80
803
    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81
762
      if (!AllowInvalidDecl && 
ND->isInvalidDecl()756
)
82
11
        return false;
83
84
751
      if (getAsTypeTemplateDecl(ND))
85
98
        return AllowTemplates;
86
87
653
      bool IsType = isa<TypeDecl>(ND) || 
isa<ObjCInterfaceDecl>(ND)106
;
88
653
      if (!IsType)
89
103
        return false;
90
91
550
      if (AllowNonTemplates)
92
550
        return true;
93
94
      // An injected-class-name of a class template (specialization) is valid
95
      // as a template or as a non-template.
96
0
      if (AllowTemplates) {
97
0
        auto *RD = dyn_cast<CXXRecordDecl>(ND);
98
0
        if (!RD || !RD->isInjectedClassName())
99
0
          return false;
100
0
        RD = cast<CXXRecordDecl>(RD->getDeclContext());
101
0
        return RD->getDescribedClassTemplate() ||
102
0
               isa<ClassTemplateSpecializationDecl>(RD);
103
0
      }
104
105
0
      return false;
106
0
    }
107
108
41
    return !WantClassName && 
candidate.isKeyword()39
;
109
41
  }
110
111
952
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
112
952
    return std::make_unique<TypeNameValidatorCCC>(*this);
113
952
  }
114
115
 private:
116
  bool AllowInvalidDecl;
117
  bool WantClassName;
118
  bool AllowTemplates;
119
  bool AllowNonTemplates;
120
};
121
122
} // end anonymous namespace
123
124
/// Determine whether the token kind starts a simple-type-specifier.
125
25.7k
bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126
25.7k
  switch (Kind) {
127
  // FIXME: Take into account the current language when deciding whether a
128
  // token kind is a valid type specifier
129
0
  case tok::kw_short:
130
0
  case tok::kw_long:
131
0
  case tok::kw___int64:
132
0
  case tok::kw___int128:
133
0
  case tok::kw_signed:
134
0
  case tok::kw_unsigned:
135
0
  case tok::kw_void:
136
0
  case tok::kw_char:
137
1
  case tok::kw_int:
138
1
  case tok::kw_half:
139
1
  case tok::kw_float:
140
1
  case tok::kw_double:
141
1
  case tok::kw___bf16:
142
1
  case tok::kw__Float16:
143
1
  case tok::kw___float128:
144
1
  case tok::kw_wchar_t:
145
1
  case tok::kw_bool:
146
1
  case tok::kw___underlying_type:
147
1
  case tok::kw___auto_type:
148
1
    return true;
149
150
23.7k
  case tok::annot_typename:
151
23.7k
  case tok::kw_char16_t:
152
23.7k
  case tok::kw_char32_t:
153
23.7k
  case tok::kw_typeof:
154
23.7k
  case tok::annot_decltype:
155
23.7k
  case tok::kw_decltype:
156
23.7k
    return getLangOpts().CPlusPlus;
157
158
0
  case tok::kw_char8_t:
159
0
    return getLangOpts().Char8;
160
161
1.92k
  default:
162
1.92k
    break;
163
1.92k
  }
164
165
1.92k
  return false;
166
1.92k
}
167
168
namespace {
169
enum class UnqualifiedTypeNameLookupResult {
170
  NotFound,
171
  FoundNonType,
172
  FoundType
173
};
174
} // end anonymous namespace
175
176
/// Tries to perform unqualified lookup of the type decls in bases for
177
/// dependent class.
178
/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179
/// type decl, \a FoundType if only type decls are found.
180
static UnqualifiedTypeNameLookupResult
181
lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182
                                SourceLocation NameLoc,
183
128
                                const CXXRecordDecl *RD) {
184
128
  if (!RD->hasDefinition())
185
2
    return UnqualifiedTypeNameLookupResult::NotFound;
186
  // Look for type decls in base classes.
187
126
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
188
126
      UnqualifiedTypeNameLookupResult::NotFound;
189
124
  for (const auto &Base : RD->bases()) {
190
124
    const CXXRecordDecl *BaseRD = nullptr;
191
124
    if (auto *BaseTT = Base.getType()->getAs<TagType>())
192
10
      BaseRD = BaseTT->getAsCXXRecordDecl();
193
114
    else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194
      // Look for type decls in dependent base classes that have known primary
195
      // templates.
196
88
      if (!TST || !TST->isDependentType())
197
0
        continue;
198
88
      auto *TD = TST->getTemplateName().getAsTemplateDecl();
199
88
      if (!TD)
200
0
        continue;
201
88
      if (auto *BasePrimaryTemplate =
202
84
          dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203
84
        if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204
82
          BaseRD = BasePrimaryTemplate;
205
2
        else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206
2
          if (const ClassTemplatePartialSpecializationDecl *PS =
207
2
                  CTD->findPartialSpecialization(Base.getType()))
208
2
            if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209
2
              BaseRD = PS;
210
2
        }
211
84
      }
212
88
    }
213
124
    if (BaseRD) {
214
76
      for (NamedDecl *ND : BaseRD->lookup(&II)) {
215
76
        if (!isa<TypeDecl>(ND))
216
24
          return UnqualifiedTypeNameLookupResult::FoundNonType;
217
52
        FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218
52
      }
219
70
      if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220
18
        switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221
0
        case UnqualifiedTypeNameLookupResult::FoundNonType:
222
0
          return UnqualifiedTypeNameLookupResult::FoundNonType;
223
10
        case UnqualifiedTypeNameLookupResult::FoundType:
224
10
          FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225
10
          break;
226
8
        case UnqualifiedTypeNameLookupResult::NotFound:
227
8
          break;
228
18
        }
229
18
      }
230
70
    }
231
124
  }
232
233
102
  return FoundTypeDecl;
234
126
}
235
236
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237
                                                      const IdentifierInfo &II,
238
170
                                                      SourceLocation NameLoc) {
239
  // Lookup in the parent class template context, if any.
240
170
  const CXXRecordDecl *RD = nullptr;
241
170
  UnqualifiedTypeNameLookupResult FoundTypeDecl =
242
170
      UnqualifiedTypeNameLookupResult::NotFound;
243
170
  for (DeclContext *DC = S.CurContext;
244
549
       DC && 
FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound447
;
245
379
       DC = DC->getParent()) {
246
    // Look for type decls in dependent base classes that have known primary
247
    // templates.
248
379
    RD = dyn_cast<CXXRecordDecl>(DC);
249
379
    if (RD && 
RD->getDescribedClassTemplate()127
)
250
110
      FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251
379
  }
252
170
  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253
126
    return nullptr;
254
255
  // We found some types in dependent base classes.  Recover as if the user
256
  // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
257
  // lookup during template instantiation.
258
44
  S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260
44
  ASTContext &Context = S.Context;
261
44
  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262
44
                                          cast<Type>(Context.getRecordType(RD)));
263
44
  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264
265
44
  CXXScopeSpec SS;
266
44
  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268
44
  TypeLocBuilder Builder;
269
44
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270
44
  DepTL.setNameLoc(NameLoc);
271
44
  DepTL.setElaboratedKeywordLoc(SourceLocation());
272
44
  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273
44
  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274
44
}
275
276
/// If the identifier refers to a type name within this scope,
277
/// return the declaration of that type.
278
///
279
/// This routine performs ordinary name lookup of the identifier II
280
/// within the given scope, with optional C++ scope specifier SS, to
281
/// determine whether the name refers to a type. If so, returns an
282
/// opaque pointer (actually a QualType) corresponding to that
283
/// type. Otherwise, returns NULL.
284
ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285
                             Scope *S, CXXScopeSpec *SS,
286
                             bool isClassName, bool HasTrailingDot,
287
                             ParsedType ObjectTypePtr,
288
                             bool IsCtorOrDtorName,
289
                             bool WantNontrivialTypeSourceInfo,
290
                             bool IsClassTemplateDeductionContext,
291
56.7M
                             IdentifierInfo **CorrectedII) {
292
  // FIXME: Consider allowing this outside C++1z mode as an extension.
293
56.7M
  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294
56.5M
                              getLangOpts().CPlusPlus17 && 
!IsCtorOrDtorName285k
&&
295
285k
                              !isClassName && !HasTrailingDot;
296
297
  // Determine where we will perform name lookup.
298
56.7M
  DeclContext *LookupCtx = nullptr;
299
56.7M
  if (ObjectTypePtr) {
300
6.77k
    QualType ObjectType = ObjectTypePtr.get();
301
6.77k
    if (ObjectType->isRecordType())
302
401
      LookupCtx = computeDeclContext(ObjectType);
303
56.7M
  } else if (SS && 
SS->isNotEmpty()19.6M
) {
304
2.23M
    LookupCtx = computeDeclContext(*SS, false);
305
306
2.23M
    if (!LookupCtx) {
307
1.44M
      if (isDependentScopeSpecifier(*SS)) {
308
        // C++ [temp.res]p3:
309
        //   A qualified-id that refers to a type and in which the
310
        //   nested-name-specifier depends on a template-parameter (14.6.2)
311
        //   shall be prefixed by the keyword typename to indicate that the
312
        //   qualified-id denotes a type, forming an
313
        //   elaborated-type-specifier (7.1.5.3).
314
        //
315
        // We therefore do not perform any name lookup if the result would
316
        // refer to a member of an unknown specialization.
317
1.44M
        if (!isClassName && 
!IsCtorOrDtorName1.43M
)
318
1.43M
          return nullptr;
319
320
        // We know from the grammar that this name refers to a type,
321
        // so build a dependent node to describe the type.
322
2.35k
        if (WantNontrivialTypeSourceInfo)
323
2.34k
          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324
325
12
        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326
12
        QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327
12
                                       II, NameLoc);
328
12
        return ParsedType::make(T);
329
12
      }
330
331
249
      return nullptr;
332
249
    }
333
334
796k
    if (!LookupCtx->isDependentContext() &&
335
795k
        RequireCompleteDeclContext(*SS, LookupCtx))
336
116
      return nullptr;
337
55.2M
  }
338
339
  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340
  // lookup for class-names.
341
55.2M
  LookupNameKind Kind = isClassName ? 
LookupNestedNameSpecifierName78.4k
:
342
55.2M
                                      LookupOrdinaryName;
343
55.2M
  LookupResult Result(*this, &II, NameLoc, Kind);
344
55.2M
  if (LookupCtx) {
345
    // Perform "qualified" name lookup into the declaration context we
346
    // computed, which is either the type of the base of a member access
347
    // expression or the declaration context associated with a prior
348
    // nested-name-specifier.
349
796k
    LookupQualifiedName(Result, LookupCtx);
350
351
796k
    if (ObjectTypePtr && 
Result.empty()0
) {
352
      // C++ [basic.lookup.classref]p3:
353
      //   If the unqualified-id is ~type-name, the type-name is looked up
354
      //   in the context of the entire postfix-expression. If the type T of
355
      //   the object expression is of a class type C, the type-name is also
356
      //   looked up in the scope of class C. At least one of the lookups shall
357
      //   find a name that refers to (possibly cv-qualified) T.
358
0
      LookupName(Result, S);
359
0
    }
360
54.4M
  } else {
361
    // Perform unqualified name lookup.
362
54.4M
    LookupName(Result, S);
363
364
    // For unqualified lookup in a class template in MSVC mode, look into
365
    // dependent base classes where the primary class template is known.
366
54.4M
    if (Result.empty() && 
getLangOpts().MSVCCompat155k
&&
(99
!SS99
||
SS->isEmpty()28
)) {
367
99
      if (ParsedType TypeInBase =
368
30
              recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369
30
        return TypeInBase;
370
55.2M
    }
371
54.4M
  }
372
373
55.2M
  NamedDecl *IIDecl = nullptr;
374
55.2M
  switch (Result.getResultKind()) {
375
155k
  case LookupResult::NotFound:
376
155k
  case LookupResult::NotFoundInCurrentInstantiation:
377
155k
    if (CorrectedII) {
378
8
      TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379
8
                               AllowDeducedTemplate);
380
8
      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381
8
                                              S, SS, CCC, CTK_ErrorRecovery);
382
8
      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383
8
      TemplateTy Template;
384
8
      bool MemberOfUnknownSpecialization;
385
8
      UnqualifiedId TemplateName;
386
8
      TemplateName.setIdentifier(NewII, NameLoc);
387
8
      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388
8
      CXXScopeSpec NewSS, *NewSSPtr = SS;
389
8
      if (SS && NNS) {
390
0
        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391
0
        NewSSPtr = &NewSS;
392
0
      }
393
8
      if (Correction && 
(2
NNS2
||
NewII != &II2
) &&
394
          // Ignore a correction to a template type as the to-be-corrected
395
          // identifier is not a template (typo correction for template names
396
          // is handled elsewhere).
397
2
          !(getLangOpts().CPlusPlus && NewSSPtr &&
398
2
            isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399
2
                           Template, MemberOfUnknownSpecialization))) {
400
2
        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401
2
                                    isClassName, HasTrailingDot, ObjectTypePtr,
402
2
                                    IsCtorOrDtorName,
403
2
                                    WantNontrivialTypeSourceInfo,
404
2
                                    IsClassTemplateDeductionContext);
405
2
        if (Ty) {
406
2
          diagnoseTypo(Correction,
407
2
                       PDiag(diag::err_unknown_type_or_class_name_suggest)
408
2
                         << Result.getLookupName() << isClassName);
409
2
          if (SS && NNS)
410
0
            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411
2
          *CorrectedII = NewII;
412
2
          return Ty;
413
2
        }
414
155k
      }
415
8
    }
416
    // If typo correction failed or was not performed, fall through
417
155k
    LLVM_FALLTHROUGH;
418
815k
  case LookupResult::FoundOverloaded:
419
815k
  case LookupResult::FoundUnresolvedValue:
420
815k
    Result.suppressDiagnostics();
421
815k
    return nullptr;
422
423
68
  case LookupResult::Ambiguous:
424
    // Recover from type-hiding ambiguities by hiding the type.  We'll
425
    // do the lookup again when looking for an object, and we can
426
    // diagnose the error then.  If we don't do this, then the error
427
    // about hiding the type will be immediately followed by an error
428
    // that only makes sense if the identifier was treated like a type.
429
68
    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430
2
      Result.suppressDiagnostics();
431
2
      return nullptr;
432
2
    }
433
434
    // Look to see if we have a type anywhere in the list of results.
435
66
    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436
186
         Res != ResEnd; 
++Res120
) {
437
120
      if (isa<TypeDecl>(*Res) || 
isa<ObjCInterfaceDecl>(*Res)61
||
438
61
          (AllowDeducedTemplate && 
getAsTypeTemplateDecl(*Res)4
)) {
439
59
        if (!IIDecl || 
(*Res)->getLocation() < IIDecl->getLocation()29
)
440
41
          IIDecl = *Res;
441
59
      }
442
120
    }
443
444
66
    if (!IIDecl) {
445
      // None of the entities we found is a type, so there is no way
446
      // to even assume that the result is a type. In this case, don't
447
      // complain about the ambiguity. The parser will either try to
448
      // perform this lookup again (e.g., as an object name), which
449
      // will produce the ambiguity, or will complain that it expected
450
      // a type name.
451
36
      Result.suppressDiagnostics();
452
36
      return nullptr;
453
36
    }
454
455
    // We found a type within the ambiguous lookup; diagnose the
456
    // ambiguity and then return that type. This might be the right
457
    // answer, or it might not be, but it suppresses any attempt to
458
    // perform the name lookup again.
459
30
    break;
460
461
54.4M
  case LookupResult::Found:
462
54.4M
    IIDecl = Result.getFoundDecl();
463
54.4M
    break;
464
54.4M
  }
465
466
54.4M
  assert(IIDecl && "Didn't find decl");
467
468
54.4M
  QualType T;
469
54.4M
  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
470
    // C++ [class.qual]p2: A lookup that would find the injected-class-name
471
    // instead names the constructors of the class, except when naming a class.
472
    // This is ill-formed when we're not actually forming a ctor or dtor name.
473
51.6M
    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
474
51.6M
    auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
475
51.6M
    if (!isClassName && 
!IsCtorOrDtorName51.5M
&&
LookupRD51.5M
&&
FoundRD35.7k
&&
476
4.18k
        FoundRD->isInjectedClassName() &&
477
72
        declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
478
52
      Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
479
52
          << &II << /*Type*/1;
480
481
51.6M
    DiagnoseUseOfDecl(IIDecl, NameLoc);
482
483
51.6M
    T = Context.getTypeDeclType(TD);
484
51.6M
    MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
485
2.81M
  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
486
1.50M
    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
487
1.50M
    if (!HasTrailingDot)
488
1.50M
      T = Context.getObjCInterfaceType(IDecl);
489
1.30M
  } else if (AllowDeducedTemplate) {
490
32.1k
    if (auto *TD = getAsTypeTemplateDecl(IIDecl))
491
1.11k
      T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
492
1.11k
                                                       QualType(), false);
493
32.1k
  }
494
495
54.4M
  if (T.isNull()) {
496
    // If it's not plausibly a type, suppress diagnostics.
497
1.30M
    Result.suppressDiagnostics();
498
1.30M
    return nullptr;
499
1.30M
  }
500
501
  // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
502
  // constructor or destructor name (in such a case, the scope specifier
503
  // will be attached to the enclosing Expr or Decl node).
504
53.1M
  if (SS && 
SS->isNotEmpty()16.1M
&&
!IsCtorOrDtorName102k
&&
505
102k
      !isa<ObjCInterfaceDecl>(IIDecl)) {
506
102k
    if (WantNontrivialTypeSourceInfo) {
507
      // Construct a type with type-source information.
508
102k
      TypeLocBuilder Builder;
509
102k
      Builder.pushTypeSpec(T).setNameLoc(NameLoc);
510
511
102k
      T = getElaboratedType(ETK_None, *SS, T);
512
102k
      ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
513
102k
      ElabTL.setElaboratedKeywordLoc(SourceLocation());
514
102k
      ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
515
102k
      return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
516
0
    } else {
517
0
      T = getElaboratedType(ETK_None, *SS, T);
518
0
    }
519
102k
  }
520
521
53.0M
  return ParsedType::make(T);
522
53.1M
}
523
524
// Builds a fake NNS for the given decl context.
525
static NestedNameSpecifier *
526
3
synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
527
3
  for (;; 
DC = DC->getLookupParent()0
) {
528
3
    DC = DC->getPrimaryContext();
529
3
    auto *ND = dyn_cast<NamespaceDecl>(DC);
530
3
    if (ND && 
!ND->isInline()2
&&
!ND->isAnonymousNamespace()2
)
531
2
      return NestedNameSpecifier::Create(Context, nullptr, ND);
532
1
    else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
533
1
      return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
534
1
                                         RD->getTypeForDecl());
535
0
    else if (isa<TranslationUnitDecl>(DC))
536
0
      return NestedNameSpecifier::GlobalSpecifier(Context);
537
3
  }
538
3
  
llvm_unreachable0
("something isn't in TU scope?");
539
3
}
540
541
/// Find the parent class with dependent bases of the innermost enclosing method
542
/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
543
/// up allowing unqualified dependent type names at class-level, which MSVC
544
/// correctly rejects.
545
static const CXXRecordDecl *
546
33
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
547
47
  for (; DC && DC->isDependentContext(); 
DC = DC->getLookupParent()14
) {
548
26
    DC = DC->getPrimaryContext();
549
26
    if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
550
12
      if (MD->getParent()->hasAnyDependentBases())
551
12
        return MD->getParent();
552
26
  }
553
21
  return nullptr;
554
33
}
555
556
ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
557
                                          SourceLocation NameLoc,
558
36
                                          bool IsTemplateTypeArg) {
559
36
  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
560
561
36
  NestedNameSpecifier *NNS = nullptr;
562
36
  if (IsTemplateTypeArg && 
getCurScope()->isTemplateParamScope()3
) {
563
    // If we weren't able to parse a default template argument, delay lookup
564
    // until instantiation time by making a non-dependent DependentTypeName. We
565
    // pretend we saw a NestedNameSpecifier referring to the current scope, and
566
    // lookup is retried.
567
    // FIXME: This hurts our diagnostic quality, since we get errors like "no
568
    // type named 'Foo' in 'current_namespace'" when the user didn't write any
569
    // name specifiers.
570
3
    NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
571
3
    Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
572
33
  } else if (const CXXRecordDecl *RD =
573
12
                 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
574
    // Build a DependentNameType that will perform lookup into RD at
575
    // instantiation time.
576
12
    NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
577
12
                                      RD->getTypeForDecl());
578
579
    // Diagnose that this identifier was undeclared, and retry the lookup during
580
    // template instantiation.
581
12
    Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
582
12
                                                                      << RD;
583
21
  } else {
584
    // This is not a situation that we should recover from.
585
21
    return ParsedType();
586
21
  }
587
588
15
  QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
589
590
  // Build type location information.  We synthesized the qualifier, so we have
591
  // to build a fake NestedNameSpecifierLoc.
592
15
  NestedNameSpecifierLocBuilder NNSLocBuilder;
593
15
  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
594
15
  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
595
596
15
  TypeLocBuilder Builder;
597
15
  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
598
15
  DepTL.setNameLoc(NameLoc);
599
15
  DepTL.setElaboratedKeywordLoc(SourceLocation());
600
15
  DepTL.setQualifierLoc(QualifierLoc);
601
15
  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
602
15
}
603
604
/// isTagName() - This method is called *for error recovery purposes only*
605
/// to determine if the specified name is a valid tag name ("struct foo").  If
606
/// so, this returns the TST for the tag corresponding to it (TST_enum,
607
/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
608
/// cases in C where the user forgot to specify the tag.
609
994
DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
610
  // Do a tag name lookup in this scope.
611
994
  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
612
994
  LookupName(R, S, false);
613
994
  R.suppressDiagnostics();
614
994
  if (R.getResultKind() == LookupResult::Found)
615
72
    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
616
34
      switch (TD->getTagKind()) {
617
14
      case TTK_Struct: return DeclSpec::TST_struct;
618
0
      case TTK_Interface: return DeclSpec::TST_interface;
619
0
      case TTK_Union:  return DeclSpec::TST_union;
620
9
      case TTK_Class:  return DeclSpec::TST_class;
621
11
      case TTK_Enum:   return DeclSpec::TST_enum;
622
960
      }
623
960
    }
624
625
960
  return DeclSpec::TST_unspecified;
626
960
}
627
628
/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
629
/// if a CXXScopeSpec's type is equal to the type of one of the base classes
630
/// then downgrade the missing typename error to a warning.
631
/// This is needed for MSVC compatibility; Example:
632
/// @code
633
/// template<class T> class A {
634
/// public:
635
///   typedef int TYPE;
636
/// };
637
/// template<class T> class B : public A<T> {
638
/// public:
639
///   A<T>::TYPE a; // no typename required because A<T> is a base class.
640
/// };
641
/// @endcode
642
19
bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
643
19
  if (CurContext->isRecord()) {
644
13
    if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
645
0
      return true;
646
647
13
    const Type *Ty = SS->getScopeRep()->getAsType();
648
649
13
    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
650
13
    for (const auto &Base : RD->bases())
651
21
      if (Ty && 
Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())20
)
652
8
        return true;
653
5
    return S->isFunctionPrototypeScope();
654
6
  }
655
6
  return CurContext->isFunctionOrMethod() || 
S->isFunctionPrototypeScope()2
;
656
6
}
657
658
void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
659
                                   SourceLocation IILoc,
660
                                   Scope *S,
661
                                   CXXScopeSpec *SS,
662
                                   ParsedType &SuggestedType,
663
1.24k
                                   bool IsTemplateName) {
664
  // Don't report typename errors for editor placeholders.
665
1.24k
  if (II->isEditorPlaceholder())
666
7
    return;
667
  // We don't have anything to suggest (yet).
668
1.23k
  SuggestedType = nullptr;
669
670
  // There may have been a typo in the name of the type. Look up typo
671
  // results, in case we have something that we can suggest.
672
1.23k
  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
673
1.23k
                           /*AllowTemplates=*/IsTemplateName,
674
1.23k
                           /*AllowNonTemplates=*/!IsTemplateName);
675
1.23k
  if (TypoCorrection Corrected =
676
323
          CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
677
323
                      CCC, CTK_ErrorRecovery)) {
678
    // FIXME: Support error recovery for the template-name case.
679
323
    bool CanRecover = !IsTemplateName;
680
323
    if (Corrected.isKeyword()) {
681
      // We corrected to a keyword.
682
12
      diagnoseTypo(Corrected,
683
0
                   PDiag(IsTemplateName ? diag::err_no_template_suggest
684
12
                                        : diag::err_unknown_typename_suggest)
685
12
                       << II);
686
12
      II = Corrected.getCorrectionAsIdentifierInfo();
687
311
    } else {
688
      // We found a similarly-named type or interface; suggest that.
689
311
      if (!SS || 
!SS->isSet()61
) {
690
250
        diagnoseTypo(Corrected,
691
2
                     PDiag(IsTemplateName ? diag::err_no_template_suggest
692
248
                                          : diag::err_unknown_typename_suggest)
693
250
                         << II, CanRecover);
694
61
      } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
695
61
        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696
61
        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697
33
                                II->getName().equals(CorrectedStr);
698
61
        diagnoseTypo(Corrected,
699
61
                     PDiag(IsTemplateName
700
0
                               ? diag::err_no_member_template_suggest
701
61
                               : diag::err_unknown_nested_typename_suggest)
702
61
                         << II << DC << DroppedSpecifier << SS->getRange(),
703
61
                     CanRecover);
704
0
      } else {
705
0
        llvm_unreachable("could not have corrected a typo here");
706
0
      }
707
708
311
      if (!CanRecover)
709
2
        return;
710
711
309
      CXXScopeSpec tmpSS;
712
309
      if (Corrected.getCorrectionSpecifier())
713
27
        tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
714
27
                          SourceRange(IILoc));
715
      // FIXME: Support class template argument deduction here.
716
309
      SuggestedType =
717
309
          getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
718
282
                      tmpSS.isSet() ? 
&tmpSS27
: SS, false, false, nullptr,
719
309
                      /*IsCtorOrDtorName=*/false,
720
309
                      /*WantNontrivialTypeSourceInfo=*/true);
721
309
    }
722
321
    return;
723
910
  }
724
725
910
  if (getLangOpts().CPlusPlus && 
!IsTemplateName734
) {
726
    // See if II is a class template that the user forgot to pass arguments to.
727
728
    UnqualifiedId Name;
728
728
    Name.setIdentifier(II, IILoc);
729
728
    CXXScopeSpec EmptySS;
730
728
    TemplateTy TemplateResult;
731
728
    bool MemberOfUnknownSpecialization;
732
728
    if (isTemplateName(S, SS ? 
*SS343
:
EmptySS385
, /*hasTemplateKeyword=*/false,
733
728
                       Name, nullptr, true, TemplateResult,
734
42
                       MemberOfUnknownSpecialization) == TNK_Type_template) {
735
42
      diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
736
42
      return;
737
42
    }
738
868
  }
739
740
  // FIXME: Should we move the logic that tries to recover from a missing tag
741
  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
742
743
868
  if (!SS || 
(329
!SS->isSet()329
&&
!SS->isInvalid()126
))
744
539
    Diag(IILoc, IsTemplateName ? 
diag::err_no_template0
745
539
                               : diag::err_unknown_typename)
746
539
        << II;
747
329
  else if (DeclContext *DC = computeDeclContext(*SS, false))
748
39
    Diag(IILoc, IsTemplateName ? 
diag::err_no_member_template6
749
33
                               : diag::err_typename_nested_not_found)
750
39
        << II << DC << SS->getRange();
751
290
  else if (SS->isValid() && 
SS->getScopeRep()->containsErrors()164
) {
752
3
    SuggestedType =
753
3
        ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
754
287
  } else if (isDependentScopeSpecifier(*SS)) {
755
161
    unsigned DiagID = diag::err_typename_missing;
756
161
    if (getLangOpts().MSVCCompat && 
isMicrosoftMissingTypename(SS, S)19
)
757
14
      DiagID = diag::ext_typename_missing;
758
759
161
    Diag(SS->getRange().getBegin(), DiagID)
760
161
      << SS->getScopeRep() << II->getName()
761
161
      << SourceRange(SS->getRange().getBegin(), IILoc)
762
161
      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
763
161
    SuggestedType = ActOnTypenameType(S, SourceLocation(),
764
161
                                      *SS, *II, IILoc).get();
765
126
  } else {
766
126
    assert(SS && SS->isInvalid() &&
767
126
           "Invalid scope specifier has already been diagnosed");
768
126
  }
769
868
}
770
771
/// Determine whether the given result set contains either a type name
772
/// or
773
4.99k
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
774
4.99k
  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
775
1.22k
                       NextToken.is(tok::less);
776
777
7.97k
  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; 
++I2.98k
) {
778
4.09k
    if (isa<TypeDecl>(*I) || 
isa<ObjCInterfaceDecl>(*I)3.53k
)
779
1.11k
      return true;
780
781
2.98k
    if (CheckTemplate && 
isa<TemplateDecl>(*I)0
)
782
0
      return true;
783
2.98k
  }
784
785
3.88k
  return false;
786
4.99k
}
787
788
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
789
                                    Scope *S, CXXScopeSpec &SS,
790
                                    IdentifierInfo *&Name,
791
6.58k
                                    SourceLocation NameLoc) {
792
6.58k
  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
793
6.58k
  SemaRef.LookupParsedName(R, S, &SS);
794
6.58k
  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
795
36
    StringRef FixItTagName;
796
36
    switch (Tag->getTagKind()) {
797
12
      case TTK_Class:
798
12
        FixItTagName = "class ";
799
12
        break;
800
801
10
      case TTK_Enum:
802
10
        FixItTagName = "enum ";
803
10
        break;
804
805
14
      case TTK_Struct:
806
14
        FixItTagName = "struct ";
807
14
        break;
808
809
0
      case TTK_Interface:
810
0
        FixItTagName = "__interface ";
811
0
        break;
812
813
0
      case TTK_Union:
814
0
        FixItTagName = "union ";
815
0
        break;
816
36
    }
817
818
36
    StringRef TagName = FixItTagName.drop_back();
819
36
    SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
820
36
      << Name << TagName << SemaRef.getLangOpts().CPlusPlus
821
36
      << FixItHint::CreateInsertion(NameLoc, FixItTagName);
822
823
36
    for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
824
68
         I != IEnd; 
++I32
)
825
32
      SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
826
32
        << Name << TagName;
827
828
    // Replace lookup results with just the tag decl.
829
36
    Result.clear(Sema::LookupTagName);
830
36
    SemaRef.LookupParsedName(Result, S, &SS);
831
36
    return true;
832
36
  }
833
834
6.55k
  return false;
835
6.55k
}
836
837
/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
838
static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
839
218
                                  QualType T, SourceLocation NameLoc) {
840
218
  ASTContext &Context = S.Context;
841
842
218
  TypeLocBuilder Builder;
843
218
  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
844
845
218
  T = S.getElaboratedType(ETK_None, SS, T);
846
218
  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
847
218
  ElabTL.setElaboratedKeywordLoc(SourceLocation());
848
218
  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
849
218
  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
850
218
}
851
852
Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
853
                                            IdentifierInfo *&Name,
854
                                            SourceLocation NameLoc,
855
                                            const Token &NextToken,
856
6.85M
                                            CorrectionCandidateCallback *CCC) {
857
6.85M
  DeclarationNameInfo NameInfo(Name, NameLoc);
858
6.85M
  ObjCMethodDecl *CurMethod = getCurMethodDecl();
859
860
6.85M
  assert(NextToken.isNot(tok::coloncolon) &&
861
6.85M
         "parse nested name specifiers before calling ClassifyName");
862
6.85M
  if (getLangOpts().CPlusPlus && 
SS.isSet()5.93M
&&
863
72.8k
      isCurrentClassName(*Name, S, &SS)) {
864
    // Per [class.qual]p2, this names the constructors of SS, not the
865
    // injected-class-name. We don't have a classification for that.
866
    // There's not much point caching this result, since the parser
867
    // will reject it later.
868
8
    return NameClassification::Unknown();
869
8
  }
870
871
6.85M
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
872
6.85M
  LookupParsedName(Result, S, &SS, !CurMethod);
873
874
6.85M
  if (SS.isInvalid())
875
5
    return NameClassification::Error();
876
877
  // For unqualified lookup in a class template in MSVC mode, look into
878
  // dependent base classes where the primary class template is known.
879
6.85M
  if (Result.empty() && 
SS.isEmpty()13.2k
&&
getLangOpts().MSVCCompat11.0k
) {
880
71
    if (ParsedType TypeInBase =
881
14
            recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
882
14
      return TypeInBase;
883
6.85M
  }
884
885
  // Perform lookup for Objective-C instance variables (including automatically
886
  // synthesized instance variables), if we're in an Objective-C method.
887
  // FIXME: This lookup really, really needs to be folded in to the normal
888
  // unqualified lookup mechanism.
889
6.85M
  if (SS.isEmpty() && 
CurMethod6.78M
&&
!isResultTypeOrTemplate(Result, NextToken)4.99k
) {
890
3.88k
    DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
891
3.88k
    if (Ivar.isInvalid())
892
6
      return NameClassification::Error();
893
3.87k
    if (Ivar.isUsable())
894
903
      return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
895
896
    // We defer builtin creation until after ivar lookup inside ObjC methods.
897
2.97k
    if (Result.empty())
898
159
      LookupBuiltin(Result);
899
2.97k
  }
900
901
6.85M
  bool SecondTry = false;
902
6.85M
  bool IsFilteredTemplateName = false;
903
904
6.85M
Corrected:
905
6.85M
  switch (Result.getResultKind()) {
906
10.3k
  case LookupResult::NotFound:
907
    // If an unqualified-id is followed by a '(', then we have a function
908
    // call.
909
10.3k
    if (SS.isEmpty() && 
NextToken.is(tok::l_paren)10.2k
) {
910
      // In C++, this is an ADL-only call.
911
      // FIXME: Reference?
912
753
      if (getLangOpts().CPlusPlus)
913
590
        return NameClassification::UndeclaredNonType();
914
915
      // C90 6.3.2.2:
916
      //   If the expression that precedes the parenthesized argument list in a
917
      //   function call consists solely of an identifier, and if no
918
      //   declaration is visible for this identifier, the identifier is
919
      //   implicitly declared exactly as if, in the innermost block containing
920
      //   the function call, the declaration
921
      //
922
      //     extern int identifier ();
923
      //
924
      //   appeared.
925
      //
926
      // We also allow this in C99 as an extension.
927
163
      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
928
163
        return NameClassification::NonType(D);
929
9.62k
    }
930
931
9.62k
    if (getLangOpts().CPlusPlus20 && 
SS.isEmpty()94
&&
NextToken.is(tok::less)86
) {
932
      // In C++20 onwards, this could be an ADL-only call to a function
933
      // template, and we're required to assume that this is a template name.
934
      //
935
      // FIXME: Find a way to still do typo correction in this case.
936
2
      TemplateName Template =
937
2
          Context.getAssumedTemplateName(NameInfo.getName());
938
2
      return NameClassification::UndeclaredTemplate(Template);
939
2
    }
940
941
    // In C, we first see whether there is a tag type by the same name, in
942
    // which case it's likely that the user just forgot to write "enum",
943
    // "struct", or "union".
944
9.62k
    if (!getLangOpts().CPlusPlus && 
!SecondTry6.36k
&&
945
6.36k
        isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
946
4
      break;
947
4
    }
948
949
    // Perform typo correction to determine if there is another name that is
950
    // close to this name.
951
9.61k
    if (!SecondTry && CCC) {
952
9.48k
      SecondTry = true;
953
9.48k
      if (TypoCorrection Corrected =
954
92
              CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
955
92
                          &SS, *CCC, CTK_ErrorRecovery)) {
956
92
        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
957
92
        unsigned QualifiedDiag = diag::err_no_member_suggest;
958
959
92
        NamedDecl *FirstDecl = Corrected.getFoundDecl();
960
92
        NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
961
92
        if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)79
&&
962
0
            UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
963
0
          UnqualifiedDiag = diag::err_no_template_suggest;
964
0
          QualifiedDiag = diag::err_no_member_template_suggest;
965
92
        } else if (UnderlyingFirstDecl &&
966
75
                   (isa<TypeDecl>(UnderlyingFirstDecl) ||
967
56
                    isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
968
54
                    isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
969
21
          UnqualifiedDiag = diag::err_unknown_typename_suggest;
970
21
          QualifiedDiag = diag::err_unknown_nested_typename_suggest;
971
21
        }
972
973
92
        if (SS.isEmpty()) {
974
92
          diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
975
0
        } else {// FIXME: is this even reachable? Test it.
976
0
          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
977
0
          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
978
0
                                  Name->getName().equals(CorrectedStr);
979
0
          diagnoseTypo(Corrected, PDiag(QualifiedDiag)
980
0
                                    << Name << computeDeclContext(SS, false)
981
0
                                    << DroppedSpecifier << SS.getRange());
982
0
        }
983
984
        // Update the name, so that the caller has the new name.
985
92
        Name = Corrected.getCorrectionAsIdentifierInfo();
986
987
        // Typo correction corrected to a keyword.
988
92
        if (Corrected.isKeyword())
989
17
          return Name;
990
991
        // Also update the LookupResult...
992
        // FIXME: This should probably go away at some point
993
75
        Result.clear();
994
75
        Result.setLookupName(Corrected.getCorrection());
995
75
        if (FirstDecl)
996
75
          Result.addDecl(FirstDecl);
997
998
        // If we found an Objective-C instance variable, let
999
        // LookupInObjCMethod build the appropriate expression to
1000
        // reference the ivar.
1001
        // FIXME: This is a gross hack.
1002
75
        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1003
5
          DeclResult R =
1004
5
              LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1005
5
          if (R.isInvalid())
1006
0
            return NameClassification::Error();
1007
5
          if (R.isUsable())
1008
5
            return NameClassification::NonType(Ivar);
1009
70
        }
1010
1011
70
        goto Corrected;
1012
70
      }
1013
9.48k
    }
1014
1015
    // We failed to correct; just fall through and let the parser deal with it.
1016
9.52k
    Result.suppressDiagnostics();
1017
9.52k
    return NameClassification::Unknown();
1018
1019
2.08k
  case LookupResult::NotFoundInCurrentInstantiation: {
1020
    // We performed name lookup into the current instantiation, and there were
1021
    // dependent bases, so we treat this result the same way as any other
1022
    // dependent nested-name-specifier.
1023
1024
    // C++ [temp.res]p2:
1025
    //   A name used in a template declaration or definition and that is
1026
    //   dependent on a template-parameter is assumed not to name a type
1027
    //   unless the applicable name lookup finds a type name or the name is
1028
    //   qualified by the keyword typename.
1029
    //
1030
    // FIXME: If the next token is '<', we might want to ask the parser to
1031
    // perform some heroics to see if we actually have a
1032
    // template-argument-list, which would indicate a missing 'template'
1033
    // keyword here.
1034
2.08k
    return NameClassification::DependentNonType();
1035
9.52k
  }
1036
1037
6.69M
  case LookupResult::Found:
1038
6.84M
  case LookupResult::FoundOverloaded:
1039
6.84M
  case LookupResult::FoundUnresolvedValue:
1040
6.84M
    break;
1041
1042
29
  case LookupResult::Ambiguous:
1043
29
    if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)26
&&
1044
0
        hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1045
0
                                      /*AllowDependent=*/false)) {
1046
      // C++ [temp.local]p3:
1047
      //   A lookup that finds an injected-class-name (10.2) can result in an
1048
      //   ambiguity in certain cases (for example, if it is found in more than
1049
      //   one base class). If all of the injected-class-names that are found
1050
      //   refer to specializations of the same class template, and if the name
1051
      //   is followed by a template-argument-list, the reference refers to the
1052
      //   class template itself and not a specialization thereof, and is not
1053
      //   ambiguous.
1054
      //
1055
      // This filtering can make an ambiguous result into an unambiguous one,
1056
      // so try again after filtering out template names.
1057
0
      FilterAcceptableTemplateNames(Result);
1058
0
      if (!Result.isAmbiguous()) {
1059
0
        IsFilteredTemplateName = true;
1060
0
        break;
1061
0
      }
1062
29
    }
1063
1064
    // Diagnose the ambiguity and return an error.
1065
29
    return NameClassification::Error();
1066
6.84M
  }
1067
1068
6.84M
  if (getLangOpts().CPlusPlus && 
NextToken.is(tok::less)5.92M
&&
1069
149
      (IsFilteredTemplateName ||
1070
149
       hasAnyAcceptableTemplateNames(
1071
149
           Result, /*AllowFunctionTemplates=*/true,
1072
149
           /*AllowDependent=*/false,
1073
149
           /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1074
128
               getLangOpts().CPlusPlus20))) {
1075
    // C++ [temp.names]p3:
1076
    //   After name lookup (3.4) finds that a name is a template-name or that
1077
    //   an operator-function-id or a literal- operator-id refers to a set of
1078
    //   overloaded functions any member of which is a function template if
1079
    //   this is followed by a <, the < is always taken as the delimiter of a
1080
    //   template-argument-list and never as the less-than operator.
1081
    // C++2a [temp.names]p2:
1082
    //   A name is also considered to refer to a template if it is an
1083
    //   unqualified-id followed by a < and name lookup finds either one
1084
    //   or more functions or finds nothing.
1085
0
    if (!IsFilteredTemplateName)
1086
0
      FilterAcceptableTemplateNames(Result);
1087
1088
0
    bool IsFunctionTemplate;
1089
0
    bool IsVarTemplate;
1090
0
    TemplateName Template;
1091
0
    if (Result.end() - Result.begin() > 1) {
1092
0
      IsFunctionTemplate = true;
1093
0
      Template = Context.getOverloadedTemplateName(Result.begin(),
1094
0
                                                   Result.end());
1095
0
    } else if (!Result.empty()) {
1096
0
      auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1097
0
          *Result.begin(), /*AllowFunctionTemplates=*/true,
1098
0
          /*AllowDependent=*/false));
1099
0
      IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1100
0
      IsVarTemplate = isa<VarTemplateDecl>(TD);
1101
1102
0
      if (SS.isNotEmpty())
1103
0
        Template =
1104
0
            Context.getQualifiedTemplateName(SS.getScopeRep(),
1105
0
                                             /*TemplateKeyword=*/false, TD);
1106
0
      else
1107
0
        Template = TemplateName(TD);
1108
0
    } else {
1109
      // All results were non-template functions. This is a function template
1110
      // name.
1111
0
      IsFunctionTemplate = true;
1112
0
      Template = Context.getAssumedTemplateName(NameInfo.getName());
1113
0
    }
1114
1115
0
    if (IsFunctionTemplate) {
1116
      // Function templates always go through overload resolution, at which
1117
      // point we'll perform the various checks (e.g., accessibility) we need
1118
      // to based on which function we selected.
1119
0
      Result.suppressDiagnostics();
1120
1121
0
      return NameClassification::FunctionTemplate(Template);
1122
0
    }
1123
1124
0
    return IsVarTemplate ? NameClassification::VarTemplate(Template)
1125
0
                         : NameClassification::TypeTemplate(Template);
1126
0
  }
1127
1128
6.84M
  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1129
6.84M
  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1130
4.43M
    DiagnoseUseOfDecl(Type, NameLoc);
1131
4.43M
    MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1132
4.43M
    QualType T = Context.getTypeDeclType(Type);
1133
4.43M
    if (SS.isNotEmpty())
1134
218
      return buildNestedType(*this, SS, T, NameLoc);
1135
4.43M
    return ParsedType::make(T);
1136
4.43M
  }
1137
1138
2.41M
  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1139
2.41M
  if (!Class) {
1140
    // FIXME: It's unfortunate that we don't have a Type node for handling this.
1141
2.40M
    if (ObjCCompatibleAliasDecl *Alias =
1142
0
            dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1143
0
      Class = Alias->getClassInterface();
1144
2.40M
  }
1145
1146
2.41M
  if (Class) {
1147
9.93k
    DiagnoseUseOfDecl(Class, NameLoc);
1148
1149
9.93k
    if (NextToken.is(tok::period)) {
1150
      // Interface. <something> is parsed as a property reference expression.
1151
      // Just return "unknown" as a fall-through for now.
1152
62
      Result.suppressDiagnostics();
1153
62
      return NameClassification::Unknown();
1154
62
    }
1155
1156
9.87k
    QualType T = Context.getObjCInterfaceType(Class);
1157
9.87k
    return ParsedType::make(T);
1158
9.87k
  }
1159
1160
2.40M
  if (isa<ConceptDecl>(FirstDecl))
1161
28
    return NameClassification::Concept(
1162
28
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1163
1164
  // We can have a type template here if we're classifying a template argument.
1165
2.40M
  if (isa<TemplateDecl>(FirstDecl) && 
!isa<FunctionTemplateDecl>(FirstDecl)102k
&&
1166
3.88k
      !isa<VarTemplateDecl>(FirstDecl))
1167
3.88k
    return NameClassification::TypeTemplate(
1168
3.88k
        TemplateName(cast<TemplateDecl>(FirstDecl)));
1169
1170
  // Check for a tag type hidden by a non-type decl in a few cases where it
1171
  // seems likely a type is wanted instead of the non-type that was found.
1172
2.40M
  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1173
2.40M
  if ((NextToken.is(tok::identifier) ||
1174
2.40M
       (NextIsOp &&
1175
13.4k
        FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1176
225
      isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1177
32
    TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1178
32
    DiagnoseUseOfDecl(Type, NameLoc);
1179
32
    QualType T = Context.getTypeDeclType(Type);
1180
32
    if (SS.isNotEmpty())
1181
0
      return buildNestedType(*this, SS, T, NameLoc);
1182
32
    return ParsedType::make(T);
1183
32
  }
1184
1185
  // If we already know which single declaration is referenced, just annotate
1186
  // that declaration directly. Defer resolving even non-overloaded class
1187
  // member accesses, as we need to defer certain access checks until we know
1188
  // the context.
1189
2.40M
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1190
2.40M
  if (Result.isSingleResult() && 
!ADL2.24M
&&
!FirstDecl->isCXXClassMember()2.07M
)
1191
1.77M
    return NameClassification::NonType(Result.getRepresentativeDecl());
1192
1193
  // Otherwise, this is an overload set that we will need to resolve later.
1194
625k
  Result.suppressDiagnostics();
1195
625k
  return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1196
625k
      Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1197
625k
      Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1198
625k
      Result.begin(), Result.end()));
1199
625k
}
1200
1201
ExprResult
1202
Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1203
590
                                             SourceLocation NameLoc) {
1204
590
  assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1205
590
  CXXScopeSpec SS;
1206
590
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1207
590
  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1208
590
}
1209
1210
ExprResult
1211
Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1212
                                            IdentifierInfo *Name,
1213
                                            SourceLocation NameLoc,
1214
2.08k
                                            bool IsAddressOfOperand) {
1215
2.08k
  DeclarationNameInfo NameInfo(Name, NameLoc);
1216
2.08k
  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1217
2.08k
                                    NameInfo, IsAddressOfOperand,
1218
2.08k
                                    /*TemplateArgs=*/nullptr);
1219
2.08k
}
1220
1221
ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1222
                                              NamedDecl *Found,
1223
                                              SourceLocation NameLoc,
1224
1.77M
                                              const Token &NextToken) {
1225
1.77M
  if (getCurMethodDecl() && 
SS.isEmpty()3.57k
)
1226
3.57k
    if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1227
908
      return BuildIvarRefExpr(S, NameLoc, Ivar);
1228
1229
  // Reconstruct the lookup result.
1230
1.77M
  LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1231
1.77M
  Result.addDecl(Found);
1232
1.77M
  Result.resolveKind();
1233
1234
1.77M
  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1235
1.77M
  return BuildDeclarationNameExpr(SS, Result, ADL);
1236
1.77M
}
1237
1238
625k
ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1239
  // For an implicit class member access, transform the result into a member
1240
  // access expression if necessary.
1241
625k
  auto *ULE = cast<UnresolvedLookupExpr>(E);
1242
625k
  if ((*ULE->decls_begin())->isCXXClassMember()) {
1243
350k
    CXXScopeSpec SS;
1244
350k
    SS.Adopt(ULE->getQualifierLoc());
1245
1246
    // Reconstruct the lookup result.
1247
350k
    LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1248
350k
                        LookupOrdinaryName);
1249
350k
    Result.setNamingClass(ULE->getNamingClass());
1250
807k
    for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; 
++I457k
)
1251
457k
      Result.addDecl(*I, I.getAccess());
1252
350k
    Result.resolveKind();
1253
350k
    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1254
350k
                                           nullptr, S);
1255
350k
  }
1256
1257
  // Otherwise, this is already in the form we needed, and no further checks
1258
  // are necessary.
1259
274k
  return ULE;
1260
274k
}
1261
1262
Sema::TemplateNameKindForDiagnostics
1263
1.32k
Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1264
1.32k
  auto *TD = Name.getAsTemplateDecl();
1265
1.32k
  if (!TD)
1266
96
    return TemplateNameKindForDiagnostics::DependentTemplate;
1267
1.23k
  if (isa<ClassTemplateDecl>(TD))
1268
257
    return TemplateNameKindForDiagnostics::ClassTemplate;
1269
973
  if (isa<FunctionTemplateDecl>(TD))
1270
910
    return TemplateNameKindForDiagnostics::FunctionTemplate;
1271
63
  if (isa<VarTemplateDecl>(TD))
1272
23
    return TemplateNameKindForDiagnostics::VarTemplate;
1273
40
  if (isa<TypeAliasTemplateDecl>(TD))
1274
28
    return TemplateNameKindForDiagnostics::AliasTemplate;
1275
12
  if (isa<TemplateTemplateParmDecl>(TD))
1276
11
    return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1277
1
  if (isa<ConceptDecl>(TD))
1278
1
    return TemplateNameKindForDiagnostics::Concept;
1279
0
  return TemplateNameKindForDiagnostics::DependentTemplate;
1280
0
}
1281
1282
5.71M
void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1283
5.71M
  assert(DC->getLexicalParent() == CurContext &&
1284
5.71M
      "The next DeclContext should be lexically contained in the current one.");
1285
5.71M
  CurContext = DC;
1286
5.71M
  S->setEntity(DC);
1287
5.71M
}
1288
1289
8.43M
void Sema::PopDeclContext() {
1290
8.43M
  assert(CurContext && "DeclContext imbalance!");
1291
1292
8.43M
  CurContext = CurContext->getLexicalParent();
1293
8.43M
  assert(CurContext && "Popped translation unit!");
1294
8.43M
}
1295
1296
Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1297
47
                                                                    Decl *D) {
1298
  // Unlike PushDeclContext, the context to which we return is not necessarily
1299
  // the containing DC of TD, because the new context will be some pre-existing
1300
  // TagDecl definition instead of a fresh one.
1301
47
  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1302
47
  CurContext = cast<TagDecl>(D)->getDefinition();
1303
47
  assert(CurContext && "skipping definition of undefined tag");
1304
  // Start lookups from the parent of the current context; we don't want to look
1305
  // into the pre-existing complete definition.
1306
47
  S->setEntity(CurContext->getLookupParent());
1307
47
  return Result;
1308
47
}
1309
1310
47
void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1311
47
  CurContext = static_cast<decltype(CurContext)>(Context);
1312
47
}
1313
1314
/// EnterDeclaratorContext - Used when we must lookup names in the context
1315
/// of a declarator's nested name specifier.
1316
///
1317
267k
void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1318
  // C++0x [basic.lookup.unqual]p13:
1319
  //   A name used in the definition of a static data member of class
1320
  //   X (after the qualified-id of the static member) is looked up as
1321
  //   if the name was used in a member function of X.
1322
  // C++0x [basic.lookup.unqual]p14:
1323
  //   If a variable member of a namespace is defined outside of the
1324
  //   scope of its namespace then any name used in the definition of
1325
  //   the variable member (after the declarator-id) is looked up as
1326
  //   if the definition of the variable member occurred in its
1327
  //   namespace.
1328
  // Both of these imply that we should push a scope whose context
1329
  // is the semantic context of the declaration.  We can't use
1330
  // PushDeclContext here because that context is not necessarily
1331
  // lexically contained in the current context.  Fortunately,
1332
  // the containing scope should have the appropriate information.
1333
1334
267k
  assert(!S->getEntity() && "scope already has entity");
1335
1336
267k
#ifndef NDEBUG
1337
267k
  Scope *Ancestor = S->getParent();
1338
527k
  while (!Ancestor->getEntity()) 
Ancestor = Ancestor->getParent()260k
;
1339
267k
  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1340
267k
#endif
1341
1342
267k
  CurContext = DC;
1343
267k
  S->setEntity(DC);
1344
1345
267k
  if (S->getParent()->isTemplateParamScope()) {
1346
    // Also set the corresponding entities for all immediately-enclosing
1347
    // template parameter scopes.
1348
214k
    EnterTemplatedContext(S->getParent(), DC);
1349
214k
  }
1350
267k
}
1351
1352
267k
void Sema::ExitDeclaratorContext(Scope *S) {
1353
267k
  assert(S->getEntity() == CurContext && "Context imbalance!");
1354
1355
  // Switch back to the lexical context.  The safety of this is
1356
  // enforced by an assert in EnterDeclaratorContext.
1357
267k
  Scope *Ancestor = S->getParent();
1358
527k
  while (!Ancestor->getEntity()) 
Ancestor = Ancestor->getParent()260k
;
1359
267k
  CurContext = Ancestor->getEntity();
1360
1361
  // We don't need to do anything with the scope, which is going to
1362
  // disappear.
1363
267k
}
1364
1365
343k
void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1366
343k
  assert(S->isTemplateParamScope() &&
1367
343k
         "expected to be initializing a template parameter scope");
1368
1369
  // C++20 [temp.local]p7:
1370
  //   In the definition of a member of a class template that appears outside
1371
  //   of the class template definition, the name of a member of the class
1372
  //   template hides the name of a template-parameter of any enclosing class
1373
  //   templates (but not a template-parameter of the member if the member is a
1374
  //   class or function template).
1375
  // C++20 [temp.local]p9:
1376
  //   In the definition of a class template or in the definition of a member
1377
  //   of such a template that appears outside of the template definition, for
1378
  //   each non-dependent base class (13.8.2.1), if the name of the base class
1379
  //   or the name of a member of the base class is the same as the name of a
1380
  //   template-parameter, the base class name or member name hides the
1381
  //   template-parameter name (6.4.10).
1382
  //
1383
  // This means that a template parameter scope should be searched immediately
1384
  // after searching the DeclContext for which it is a template parameter
1385
  // scope. For example, for
1386
  //   template<typename T> template<typename U> template<typename V>
1387
  //     void N::A<T>::B<U>::f(...)
1388
  // we search V then B<U> (and base classes) then U then A<T> (and base
1389
  // classes) then T then N then ::.
1390
343k
  unsigned ScopeDepth = getTemplateDepth(S);
1391
732k
  for (; S && S->isTemplateParamScope(); 
S = S->getParent(), --ScopeDepth389k
) {
1392
389k
    DeclContext *SearchDCAfterScope = DC;
1393
403k
    for (; DC; 
DC = DC->getLookupParent()13.9k
) {
1394
399k
      if (const TemplateParameterList *TPL =
1395
385k
              cast<Decl>(DC)->getDescribedTemplateParams()) {
1396
385k
        unsigned DCDepth = TPL->getDepth() + 1;
1397
385k
        if (DCDepth > ScopeDepth)
1398
0
          continue;
1399
385k
        if (ScopeDepth == DCDepth)
1400
340k
          SearchDCAfterScope = DC = DC->getLookupParent();
1401
385k
        break;
1402
385k
      }
1403
399k
    }
1404
389k
    S->setLookupEntity(SearchDCAfterScope);
1405
389k
  }
1406
343k
}
1407
1408
7.50k
void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1409
  // We assume that the caller has already called
1410
  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1411
7.50k
  FunctionDecl *FD = D->getAsFunction();
1412
7.50k
  if (!FD)
1413
0
    return;
1414
1415
  // Same implementation as PushDeclContext, but enters the context
1416
  // from the lexical parent, rather than the top-level class.
1417
7.50k
  assert(CurContext == FD->getLexicalParent() &&
1418
7.50k
    "The next DeclContext should be lexically contained in the current one.");
1419
7.50k
  CurContext = FD;
1420
7.50k
  S->setEntity(CurContext);
1421
1422
17.8k
  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; 
++P10.3k
) {
1423
10.3k
    ParmVarDecl *Param = FD->getParamDecl(P);
1424
    // If the parameter has an identifier, then add it to the scope
1425
10.3k
    if (Param->getIdentifier()) {
1426
10.3k
      S->AddDecl(Param);
1427
10.3k
      IdResolver.AddDecl(Param);
1428
10.3k
    }
1429
10.3k
  }
1430
7.50k
}
1431
1432
7.50k
void Sema::ActOnExitFunctionContext() {
1433
  // Same implementation as PopDeclContext, but returns to the lexical parent,
1434
  // rather than the top-level class.
1435
7.50k
  assert(CurContext && "DeclContext imbalance!");
1436
7.50k
  CurContext = CurContext->getLexicalParent();
1437
7.50k
  assert(CurContext && "Popped translation unit!");
1438
7.50k
}
1439
1440
/// Determine whether we allow overloading of the function
1441
/// PrevDecl with another declaration.
1442
///
1443
/// This routine determines whether overloading is possible, not
1444
/// whether some new function is actually an overload. It will return
1445
/// true in C++ (where we can always provide overloads) or, as an
1446
/// extension, in C when the previous function is already an
1447
/// overloaded function declaration or has the "overloadable"
1448
/// attribute.
1449
static bool AllowOverloadingOfFunction(LookupResult &Previous,
1450
                                       ASTContext &Context,
1451
7.82M
                                       const FunctionDecl *New) {
1452
7.82M
  if (Context.getLangOpts().CPlusPlus)
1453
1.47M
    return true;
1454
1455
6.35M
  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1456
5.39M
    return true;
1457
1458
960k
  return Previous.getResultKind() == LookupResult::Found &&
1459
960k
         (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1460
21.6k
          New->hasAttr<OverloadableAttr>());
1461
960k
}
1462
1463
/// Add this decl to the scope shadowed decl chains.
1464
36.8M
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1465
  // Move up the scope chain until we find the nearest enclosing
1466
  // non-transparent context. The declaration will be introduced into this
1467
  // scope.
1468
38.0M
  while (S->getEntity() && 
S->getEntity()->isTransparentContext()37.6M
)
1469
1.12M
    S = S->getParent();
1470
1471
  // Add scoped declarations into their context, so that they can be
1472
  // found later. Declarations without a context won't be inserted
1473
  // into any context.
1474
36.8M
  if (AddToContext)
1475
36.6M
    CurContext->addDecl(D);
1476
1477
  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1478
  // are function-local declarations.
1479
36.8M
  if (getLangOpts().CPlusPlus && 
D->isOutOfLine()10.4M
&&
!S->getFnParent()228k
)
1480
227k
    return;
1481
1482
  // Template instantiations should also not be pushed into scope.
1483
36.6M
  if (isa<FunctionDecl>(D) &&
1484
14.1M
      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1485
1.46k
    return;
1486
1487
  // If this replaces anything in the current scope,
1488
36.6M
  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1489
36.6M
                               IEnd = IdResolver.end();
1490
84.4M
  for (; I != IEnd; 
++I47.7M
) {
1491
48.1M
    if (S->isDeclScope(*I) && 
D->declarationReplaces(*I)47.0M
) {
1492
379k
      S->RemoveDecl(*I);
1493
379k
      IdResolver.RemoveDecl(*I);
1494
1495
      // Should only need to replace one decl.
1496
379k
      break;
1497
379k
    }
1498
48.1M
  }
1499
1500
36.6M
  S->AddDecl(D);
1501
1502
36.6M
  if (isa<LabelDecl>(D) && 
!cast<LabelDecl>(D)->isGnuLocal()4.37k
) {
1503
    // Implicitly-generated labels may end up getting generated in an order that
1504
    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1505
    // the label at the appropriate place in the identifier chain.
1506
4.38k
    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; 
++I17
) {
1507
312
      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1508
312
      if (IDC == CurContext) {
1509
17
        if (!S->isDeclScope(*I))
1510
3
          continue;
1511
295
      } else if (IDC->Encloses(CurContext))
1512
295
        break;
1513
312
    }
1514
1515
4.36k
    IdResolver.InsertDeclAfter(I, D);
1516
36.6M
  } else {
1517
36.6M
    IdResolver.AddDecl(D);
1518
36.6M
  }
1519
36.6M
}
1520
1521
bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1522
48.8M
                         bool AllowInlineNamespace) {
1523
48.8M
  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1524
48.8M
}
1525
1526
41.0k
Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1527
41.0k
  DeclContext *TargetDC = DC->getPrimaryContext();
1528
125k
  do {
1529
125k
    if (DeclContext *ScopeDC = S->getEntity())
1530
85.2k
      if (ScopeDC->getPrimaryContext() == TargetDC)
1531
40.3k
        return S;
1532
85.5k
  } while ((S = S->getParent()));
1533
1534
752
  return nullptr;
1535
41.0k
}
1536
1537
static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1538
                                            DeclContext*,
1539
                                            ASTContext&);
1540
1541
/// Filters out lookup results that don't fall within the given scope
1542
/// as determined by isDeclInScope.
1543
void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1544
                                bool ConsiderLinkage,
1545
19.1M
                                bool AllowInlineNamespace) {
1546
19.1M
  LookupResult::Filter F = R.makeFilter();
1547
67.5M
  while (F.hasNext()) {
1548
48.4M
    NamedDecl *D = F.next();
1549
1550
48.4M
    if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1551
48.1M
      continue;
1552
1553
297k
    if (ConsiderLinkage && 
isOutOfScopePreviousDeclaration(D, Ctx, Context)1.29k
)
1554
510
      continue;
1555
1556
297k
    F.erase();
1557
297k
  }
1558
1559
19.1M
  F.done();
1560
19.1M
}
1561
1562
/// We've determined that \p New is a redeclaration of \p Old. Check that they
1563
/// have compatible owning modules.
1564
440k
bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1565
  // FIXME: The Modules TS is not clear about how friend declarations are
1566
  // to be treated. It's not meaningful to have different owning modules for
1567
  // linkage in redeclarations of the same entity, so for now allow the
1568
  // redeclaration and change the owning modules to match.
1569
440k
  if (New->getFriendObjectKind() &&
1570
22.7k
      Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1571
0
    New->setLocalOwningModule(Old->getOwningModule());
1572
0
    makeMergedDefinitionVisible(New);
1573
0
    return false;
1574
0
  }
1575
1576
440k
  Module *NewM = New->getOwningModule();
1577
440k
  Module *OldM = Old->getOwningModule();
1578
1579
440k
  if (NewM && 
NewM->Kind == Module::PrivateModuleFragment36.6k
)
1580
3
    NewM = NewM->Parent;
1581
440k
  if (OldM && 
OldM->Kind == Module::PrivateModuleFragment38.6k
)
1582
0
    OldM = OldM->Parent;
1583
1584
440k
  if (NewM == OldM)
1585
431k
    return false;
1586
1587
9.56k
  bool NewIsModuleInterface = NewM && 
NewM->isModulePurview()7.58k
;
1588
9.56k
  bool OldIsModuleInterface = OldM && 
OldM->isModulePurview()9.55k
;
1589
9.56k
  if (NewIsModuleInterface || 
OldIsModuleInterface9.51k
) {
1590
    // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1591
    //   if a declaration of D [...] appears in the purview of a module, all
1592
    //   other such declarations shall appear in the purview of the same module
1593
53
    Diag(New->getLocation(), diag::err_mismatched_owning_module)
1594
53
      << New
1595
53
      << NewIsModuleInterface
1596
46
      << (NewIsModuleInterface ? NewM->getFullModuleName() : 
""7
)
1597
53
      << OldIsModuleInterface
1598
28
      << (OldIsModuleInterface ? OldM->getFullModuleName() : 
""25
);
1599
53
    Diag(Old->getLocation(), diag::note_previous_declaration);
1600
53
    New->setInvalidDecl();
1601
53
    return true;
1602
53
  }
1603
1604
9.50k
  return false;
1605
9.50k
}
1606
1607
889k
static bool isUsingDecl(NamedDecl *D) {
1608
889k
  return isa<UsingShadowDecl>(D) ||
1609
889k
         isa<UnresolvedUsingTypenameDecl>(D) ||
1610
889k
         isa<UnresolvedUsingValueDecl>(D);
1611
889k
}
1612
1613
/// Removes using shadow declarations from the lookup results.
1614
203k
static void RemoveUsingDecls(LookupResult &R) {
1615
203k
  LookupResult::Filter F = R.makeFilter();
1616
1.09M
  while (F.hasNext())
1617
889k
    if (isUsingDecl(F.next()))
1618
8
      F.erase();
1619
1620
203k
  F.done();
1621
203k
}
1622
1623
/// Check for this common pattern:
1624
/// @code
1625
/// class S {
1626
///   S(const S&); // DO NOT IMPLEMENT
1627
///   void operator=(const S&); // DO NOT IMPLEMENT
1628
/// };
1629
/// @endcode
1630
310k
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1631
  // FIXME: Should check for private access too but access is set after we get
1632
  // the decl here.
1633
310k
  if (D->doesThisDeclarationHaveABody())
1634
523
    return false;
1635
1636
309k
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1637
84.1k
    return CD->isCopyConstructor();
1638
225k
  return D->isCopyAssignmentOperator();
1639
225k
}
1640
1641
// We need this to handle
1642
//
1643
// typedef struct {
1644
//   void *foo() { return 0; }
1645
// } A;
1646
//
1647
// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1648
// for example. If 'A', foo will have external linkage. If we have '*A',
1649
// foo will have no linkage. Since we can't know until we get to the end
1650
// of the typedef, this function finds out if D might have non-external linkage.
1651
// Callers should verify at the end of the TU if it D has external linkage or
1652
// not.
1653
4.35M
bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1654
4.35M
  const DeclContext *DC = D->getDeclContext();
1655
6.62M
  while (!DC->isTranslationUnit()) {
1656
2.26M
    if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1657
422k
      if (!RD->hasNameForLinkage())
1658
733
        return true;
1659
2.26M
    }
1660
2.26M
    DC = DC->getParent();
1661
2.26M
  }
1662
1663
4.35M
  return !D->isExternallyVisible();
1664
4.35M
}
1665
1666
// FIXME: This needs to be refactored; some other isInMainFile users want
1667
// these semantics.
1668
11.3M
static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1669
11.3M
  if (S.TUKind != TU_Complete)
1670
124k
    return false;
1671
11.1M
  return S.SourceMgr.isInMainFile(Loc);
1672
11.1M
}
1673
1674
15.9M
bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1675
15.9M
  assert(D);
1676
1677
15.9M
  if (D->isInvalidDecl() || 
D->isUsed()15.9M
||
D->hasAttr<UnusedAttr>()15.8M
)
1678
14.2k
    return false;
1679
1680
  // Ignore all entities declared within templates, and out-of-line definitions
1681
  // of members of class templates.
1682
15.8M
  if (D->getDeclContext()->isDependentContext() ||
1683
14.7M
      D->getLexicalDeclContext()->isDependentContext())
1684
1.15M
    return false;
1685
1686
14.7M
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1687
13.3M
    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1688
2.80k
      return false;
1689
    // A non-out-of-line declaration of a member specialization was implicitly
1690
    // instantiated; it's the out-of-line declaration that we're interested in.
1691
13.3M
    if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1692
8.83k
        FD->getMemberSpecializationInfo() && 
!FD->isOutOfLine()2.70k
)
1693
43
      return false;
1694
1695
13.3M
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1696
346k
      if (MD->isVirtual() || 
IsDisallowedCopyOrAssign(MD)310k
)
1697
64.5k
        return false;
1698
13.0M
    } else {
1699
      // 'static inline' functions are defined in headers; don't warn.
1700
13.0M
      if (FD->isInlined() && 
!isMainFileLoc(*this, FD->getLocation())9.93M
)
1701
9.93M
        return false;
1702
3.35M
    }
1703
1704
3.35M
    if (FD->doesThisDeclarationHaveABody() &&
1705
32.1k
        Context.DeclMustBeEmitted(FD))
1706
198
      return false;
1707
1.38M
  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1708
    // Constants and utility variables are defined in headers with internal
1709
    // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1710
    // like "inline".)
1711
1.38M
    if (!isMainFileLoc(*this, VD->getLocation()))
1712
1.29M
      return false;
1713
1714
85.8k
    if (Context.DeclMustBeEmitted(VD))
1715
54.3k
      return false;
1716
1717
31.4k
    if (VD->isStaticDataMember() &&
1718
5.71k
        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1719
0
      return false;
1720
31.4k
    if (VD->isStaticDataMember() &&
1721
5.71k
        VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1722
233
        VD->getMemberSpecializationInfo() && 
!VD->isOutOfLine()157
)
1723
112
      return false;
1724
1725
31.3k
    if (VD->isInline() && 
!isMainFileLoc(*this, VD->getLocation())231
)
1726
0
      return false;
1727
0
  } else {
1728
0
    return false;
1729
0
  }
1730
1731
  // Only warn for unused decls internal to the translation unit.
1732
  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1733
  // for inline functions defined in the main source file, for instance.
1734
3.38M
  return mightHaveNonExternalLinkage(D);
1735
3.38M
}
1736
1737
15.5M
void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1738
15.5M
  if (!D)
1739
0
    return;
1740
1741
15.5M
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1742
14.0M
    const FunctionDecl *First = FD->getFirstDecl();
1743
14.0M
    if (FD != First && 
ShouldWarnIfUnusedFileScopedDecl(First)230k
)
1744
364
      return; // First should already be in the vector.
1745
15.5M
  }
1746
1747
15.5M
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1748
1.53M
    const VarDecl *First = VD->getFirstDecl();
1749
1.53M
    if (VD != First && 
ShouldWarnIfUnusedFileScopedDecl(First)48.2k
)
1750
98
      return; // First should already be in the vector.
1751
15.5M
  }
1752
1753
15.5M
  if (ShouldWarnIfUnusedFileScopedDecl(D))
1754
39.6k
    UnusedFileScopedDecls.push_back(D);
1755
15.5M
}
1756
1757
52.7M
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1758
52.7M
  if (D->isInvalidDecl())
1759
139
    return false;
1760
1761
52.7M
  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1762
    // For a decomposition declaration, warn if none of the bindings are
1763
    // referenced, instead of if the variable itself is referenced (which
1764
    // it is, by the bindings' expressions).
1765
178
    for (auto *BD : DD->bindings())
1766
252
      if (BD->isReferenced())
1767
107
        return false;
1768
52.7M
  } else if (!D->getDeclName()) {
1769
24.0M
    return false;
1770
28.7M
  } else if (D->isReferenced() || 
D->isUsed()19.3M
) {
1771
9.34M
    return false;
1772
9.34M
  }
1773
1774
19.3M
  if (D->hasAttr<UnusedAttr>() || 
D->hasAttr<ObjCPreciseLifetimeAttr>()19.3M
)
1775
879
    return false;
1776
1777
19.3M
  if (isa<LabelDecl>(D))
1778
236
    return true;
1779
1780
  // Except for labels, we only care about unused decls that are local to
1781
  // functions.
1782
19.3M
  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1783
19.3M
  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1784
    // For dependent types, the diagnostic is deferred.
1785
2.93M
    WithinFunction =
1786
2.93M
        WithinFunction || (R->isLocalClass() && 
!R->isDependentType()31.6k
);
1787
19.3M
  if (!WithinFunction)
1788
17.7M
    return false;
1789
1790
1.61M
  if (isa<TypedefNameDecl>(D))
1791
592
    return true;
1792
1793
  // White-list anything that isn't a local variable.
1794
1.61M
  if (!isa<VarDecl>(D) || 
isa<ParmVarDecl>(D)1.48M
||
isa<ImplicitParamDecl>(D)51.3k
)
1795
1.56M
    return false;
1796
1797
  // Types of valid local variables should be complete, so this should succeed.
1798
40.2k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1799
1800
    // White-list anything with an __attribute__((unused)) type.
1801
40.2k
    const auto *Ty = VD->getType().getTypePtr();
1802
1803
    // Only look at the outermost level of typedef.
1804
40.2k
    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1805
3.21k
      if (TT->getDecl()->hasAttr<UnusedAttr>())
1806
5
        return false;
1807
40.2k
    }
1808
1809
    // If we failed to complete the type for some reason, or if the type is
1810
    // dependent, don't diagnose the variable.
1811
40.2k
    if (Ty->isIncompleteType() || 
Ty->isDependentType()40.1k
)
1812
5.14k
      return false;
1813
1814
    // Look at the element type to ensure that the warning behaviour is
1815
    // consistent for both scalars and arrays.
1816
35.0k
    Ty = Ty->getBaseElementTypeUnsafe();
1817
1818
35.0k
    if (const TagType *TT = Ty->getAs<TagType>()) {
1819
10.4k
      const TagDecl *Tag = TT->getDecl();
1820
10.4k
      if (Tag->hasAttr<UnusedAttr>())
1821
4
        return false;
1822
1823
10.4k
      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1824
9.41k
        if (!RD->hasTrivialDestructor() && 
!RD->hasAttr<WarnUnusedAttr>()3.19k
)
1825
3.19k
          return false;
1826
1827
6.21k
        if (const Expr *Init = VD->getInit()) {
1828
6.20k
          if (const ExprWithCleanups *Cleanups =
1829
1.71k
                  dyn_cast<ExprWithCleanups>(Init))
1830
1.71k
            Init = Cleanups->getSubExpr();
1831
6.20k
          const CXXConstructExpr *Construct =
1832
6.20k
            dyn_cast<CXXConstructExpr>(Init);
1833
6.20k
          if (Construct && 
!Construct->isElidable()5.27k
) {
1834
3.82k
            CXXConstructorDecl *CD = Construct->getConstructor();
1835
3.82k
            if (!CD->isTrivial() && 
!RD->hasAttr<WarnUnusedAttr>()2.19k
&&
1836
2.19k
                (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1837
2.06k
              return false;
1838
4.13k
          }
1839
1840
          // Suppress the warning if we don't know how this is constructed, and
1841
          // it could possibly be non-trivial constructor.
1842
4.13k
          if (Init->isTypeDependent())
1843
76
            for (const CXXConstructorDecl *Ctor : RD->ctors())
1844
74
              if (!Ctor->isTrivial())
1845
18
                return false;
1846
4.13k
        }
1847
6.21k
      }
1848
10.4k
    }
1849
1850
    // TODO: __attribute__((unused)) templates?
1851
35.0k
  }
1852
1853
29.8k
  return true;
1854
40.2k
}
1855
1856
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1857
30.0k
                                     FixItHint &Hint) {
1858
30.0k
  if (isa<LabelDecl>(D)) {
1859
236
    SourceLocation AfterColon = Lexer::findLocationAfterToken(
1860
236
        D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1861
236
        true);
1862
236
    if (AfterColon.isInvalid())
1863
8
      return;
1864
228
    Hint = FixItHint::CreateRemoval(
1865
228
        CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1866
228
  }
1867
30.0k
}
1868
1869
1.52M
void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1870
1.52M
  if (D->getTypeForDecl()->isDependentType())
1871
370k
    return;
1872
1873
1.15M
  for (auto *TmpD : D->decls()) {
1874
471k
    if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1875
12.8k
      DiagnoseUnusedDecl(T);
1876
458k
    else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1877
69.1k
      DiagnoseUnusedNestedTypedefs(R);
1878
471k
  }
1879
1.15M
}
1880
1881
/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1882
/// unless they are marked attr(unused).
1883
52.7M
void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1884
52.7M
  if (!ShouldDiagnoseUnusedDecl(D))
1885
52.7M
    return;
1886
1887
30.6k
  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1888
    // typedefs can be referenced later on, so the diagnostics are emitted
1889
    // at end-of-translation-unit.
1890
592
    UnusedLocalTypedefNameCandidates.insert(TD);
1891
592
    return;
1892
592
  }
1893
1894
30.0k
  FixItHint Hint;
1895
30.0k
  GenerateFixForUnusedDecl(D, Context, Hint);
1896
1897
30.0k
  unsigned DiagID;
1898
30.0k
  if (isa<VarDecl>(D) && 
cast<VarDecl>(D)->isExceptionVariable()29.8k
)
1899
361
    DiagID = diag::warn_unused_exception_param;
1900
29.6k
  else if (isa<LabelDecl>(D))
1901
236
    DiagID = diag::warn_unused_label;
1902
29.4k
  else
1903
29.4k
    DiagID = diag::warn_unused_variable;
1904
1905
30.0k
  Diag(D->getLocation(), DiagID) << D << Hint;
1906
30.0k
}
1907
1908
4.37k
static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1909
  // Verify that we have no forward references left.  If so, there was a goto
1910
  // or address of a label taken, but no definition of it.  Label fwd
1911
  // definitions are indicated with a null substmt which is also not a resolved
1912
  // MS inline assembly label name.
1913
4.37k
  bool Diagnose = false;
1914
4.37k
  if (L->isMSAsmLabel())
1915
28
    Diagnose = !L->isResolvedMSAsmLabel();
1916
4.35k
  else
1917
4.35k
    Diagnose = L->getStmt() == nullptr;
1918
4.37k
  if (Diagnose)
1919
358
    S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1920
4.37k
}
1921
1922
24.2M
void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1923
24.2M
  S->mergeNRVOIntoParent();
1924
1925
24.2M
  if (S->decl_empty()) 
return3.86M
;
1926
20.3M
  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1927
20.3M
         "Scope shouldn't contain decls!");
1928
1929
52.8M
  for (auto *TmpD : S->decls()) {
1930
52.8M
    assert(TmpD && "This decl didn't get pushed??");
1931
1932
52.8M
    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1933
52.8M
    NamedDecl *D = cast<NamedDecl>(TmpD);
1934
1935
    // Diagnose unused variables in this scope.
1936
52.8M
    if (!S->hasUnrecoverableErrorOccurred()) {
1937
52.7M
      DiagnoseUnusedDecl(D);
1938
52.7M
      if (const auto *RD = dyn_cast<RecordDecl>(D))
1939
716k
        DiagnoseUnusedNestedTypedefs(RD);
1940
52.7M
    }
1941
1942
52.8M
    if (!D->getDeclName()) 
continue24.0M
;
1943
1944
    // If this was a forward reference to a label, verify it was defined.
1945
28.7M
    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1946
4.37k
      CheckPoppedLabel(LD, *this);
1947
1948
    // Remove this name from our lexical scope, and warn on it if we haven't
1949
    // already.
1950
28.7M
    IdResolver.RemoveDecl(D);
1951
28.7M
    auto ShadowI = ShadowingDecls.find(D);
1952
28.7M
    if (ShadowI != ShadowingDecls.end()) {
1953
4
      if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1954
4
        Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1955
4
            << D << FD << FD->getParent();
1956
4
        Diag(FD->getLocation(), diag::note_previous_declaration);
1957
4
      }
1958
4
      ShadowingDecls.erase(ShadowI);
1959
4
    }
1960
28.7M
  }
1961
20.3M
}
1962
1963
/// Look for an Objective-C class in the translation unit.
1964
///
1965
/// \param Id The name of the Objective-C class we're looking for. If
1966
/// typo-correction fixes this name, the Id will be updated
1967
/// to the fixed name.
1968
///
1969
/// \param IdLoc The location of the name in the translation unit.
1970
///
1971
/// \param DoTypoCorrection If true, this routine will attempt typo correction
1972
/// if there is no class with the given name.
1973
///
1974
/// \returns The declaration of the named Objective-C class, or NULL if the
1975
/// class could not be found.
1976
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1977
                                              SourceLocation IdLoc,
1978
54.0k
                                              bool DoTypoCorrection) {
1979
  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1980
  // creation from this context.
1981
54.0k
  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1982
1983
54.0k
  if (!IDecl && 
DoTypoCorrection112
) {
1984
    // Perform typo correction at the given location, but only if we
1985
    // find an Objective-C class name.
1986
35
    DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1987
35
    if (TypoCorrection C =
1988
1
            CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1989
1
                        TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1990
1
      diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1991
1
      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1992
1
      Id = IDecl->getIdentifier();
1993
1
    }
1994
35
  }
1995
54.0k
  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1996
  // This routine must always return a class definition, if any.
1997
54.0k
  if (Def && 
Def->getDefinition()53.9k
)
1998
53.8k
      Def = Def->getDefinition();
1999
54.0k
  return Def;
2000
54.0k
}
2001
2002
/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2003
/// from S, where a non-field would be declared. This routine copes
2004
/// with the difference between C and C++ scoping rules in structs and
2005
/// unions. For example, the following code is well-formed in C but
2006
/// ill-formed in C++:
2007
/// @code
2008
/// struct S6 {
2009
///   enum { BAR } e;
2010
/// };
2011
///
2012
/// void test_S6() {
2013
///   struct S6 a;
2014
///   a.e = BAR;
2015
/// }
2016
/// @endcode
2017
/// For the declaration of BAR, this routine will return a different
2018
/// scope. The scope S will be the scope of the unnamed enumeration
2019
/// within S6. In C++, this routine will return the scope associated
2020
/// with S6, because the enumeration's scope is a transparent
2021
/// context but structures can contain non-field names. In C, this
2022
/// routine will return the translation unit scope, since the
2023
/// enumeration's scope is a transparent context and structures cannot
2024
/// contain non-field names.
2025
7.14M
Scope *Sema::getNonFieldDeclScope(Scope *S) {
2026
12.6M
  while (((S->getFlags() & Scope::DeclScope) == 0) ||
2027
12.6M
         (S->getEntity() && 
S->getEntity()->isTransparentContext()12.6M
) ||
2028
7.14M
         (S->isClassScope() && 
!getLangOpts().CPlusPlus83.3k
))
2029
5.54M
    S = S->getParent();
2030
7.14M
  return S;
2031
7.14M
}
2032
2033
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2034
5
                               ASTContext::GetBuiltinTypeError Error) {
2035
5
  switch (Error) {
2036
0
  case ASTContext::GE_None:
2037
0
    return "";
2038
0
  case ASTContext::GE_Missing_type:
2039
0
    return BuiltinInfo.getHeaderName(ID);
2040
5
  case ASTContext::GE_Missing_stdio:
2041
5
    return "stdio.h";
2042
0
  case ASTContext::GE_Missing_setjmp:
2043
0
    return "setjmp.h";
2044
0
  case ASTContext::GE_Missing_ucontext:
2045
0
    return "ucontext.h";
2046
0
  }
2047
0
  llvm_unreachable("unhandled error kind");
2048
0
}
2049
2050
FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2051
730k
                                  unsigned ID, SourceLocation Loc) {
2052
730k
  DeclContext *Parent = Context.getTranslationUnitDecl();
2053
2054
730k
  if (getLangOpts().CPlusPlus) {
2055
79.2k
    LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2056
79.2k
        Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2057
79.2k
    CLinkageDecl->setImplicit();
2058
79.2k
    Parent->addDecl(CLinkageDecl);
2059
79.2k
    Parent = CLinkageDecl;
2060
79.2k
  }
2061
2062
730k
  FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2063
730k
                                           /*TInfo=*/nullptr, SC_Extern, false,
2064
730k
                                           Type->isFunctionProtoType());
2065
730k
  New->setImplicit();
2066
730k
  New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2067
2068
  // Create Decl objects for each parameter, adding them to the
2069
  // FunctionDecl.
2070
730k
  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2071
728k
    SmallVector<ParmVarDecl *, 16> Params;
2072
2.06M
    for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i1.33M
) {
2073
1.33M
      ParmVarDecl *parm = ParmVarDecl::Create(
2074
1.33M
          Context, New, SourceLocation(), SourceLocation(), nullptr,
2075
1.33M
          FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2076
1.33M
      parm->setScopeInfo(0, i);
2077
1.33M
      Params.push_back(parm);
2078
1.33M
    }
2079
728k
    New->setParams(Params);
2080
728k
  }
2081
2082
730k
  AddKnownFunctionAttributes(New);
2083
730k
  return New;
2084
730k
}
2085
2086
/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2087
/// file scope.  lazily create a decl for it. ForRedeclaration is true
2088
/// if we're creating this built-in in anticipation of redeclaring the
2089
/// built-in.
2090
NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2091
                                     Scope *S, bool ForRedeclaration,
2092
730k
                                     SourceLocation Loc) {
2093
730k
  LookupNecessaryTypesForBuiltin(S, ID);
2094
2095
730k
  ASTContext::GetBuiltinTypeError Error;
2096
730k
  QualType R = Context.GetBuiltinType(ID, Error);
2097
730k
  if (Error) {
2098
24
    if (!ForRedeclaration)
2099
2
      return nullptr;
2100
2101
    // If we have a builtin without an associated type we should not emit a
2102
    // warning when we were not able to find a type for it.
2103
22
    if (Error == ASTContext::GE_Missing_type ||
2104
15
        Context.BuiltinInfo.allowTypeMismatch(ID))
2105
17
      return nullptr;
2106
2107
    // If we could not find a type for setjmp it is because the jmp_buf type was
2108
    // not defined prior to the setjmp declaration.
2109
5
    if (Error == ASTContext::GE_Missing_setjmp) {
2110
0
      Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2111
0
          << Context.BuiltinInfo.getName(ID);
2112
0
      return nullptr;
2113
0
    }
2114
2115
    // Generally, we emit a warning that the declaration requires the
2116
    // appropriate header.
2117
5
    Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2118
5
        << getHeaderName(Context.BuiltinInfo, ID, Error)
2119
5
        << Context.BuiltinInfo.getName(ID);
2120
5
    return nullptr;
2121
5
  }
2122
2123
730k
  if (!ForRedeclaration &&
2124
719k
      (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2125
718k
       Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2126
1.20k
    Diag(Loc, diag::ext_implicit_lib_function_decl)
2127
1.20k
        << Context.BuiltinInfo.getName(ID) << R;
2128
1.20k
    if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2129
1.20k
      Diag(Loc, diag::note_include_header_or_declare)
2130
1.20k
          << Header << Context.BuiltinInfo.getName(ID);
2131
1.20k
  }
2132
2133
730k
  if (R.isNull())
2134
8
    return nullptr;
2135
2136
730k
  FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2137
730k
  RegisterLocallyScopedExternCDecl(New, S);
2138
2139
  // TUScope is the translation-unit scope to insert this function into.
2140
  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2141
  // relate Scopes to DeclContexts, and probably eliminate CurContext
2142
  // entirely, but we're not there yet.
2143
730k
  DeclContext *SavedContext = CurContext;
2144
730k
  CurContext = New->getDeclContext();
2145
730k
  PushOnScopeChains(New, TUScope);
2146
730k
  CurContext = SavedContext;
2147
730k
  return New;
2148
730k
}
2149
2150
/// Typedef declarations don't have linkage, but they still denote the same
2151
/// entity if their types are the same.
2152
/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2153
/// isSameEntity.
2154
static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2155
                                                     TypedefNameDecl *Decl,
2156
2.30M
                                                     LookupResult &Previous) {
2157
  // This is only interesting when modules are enabled.
2158
2.30M
  if (!S.getLangOpts().Modules && 
!S.getLangOpts().ModulesLocalVisibility2.18M
)
2159
2.18M
    return;
2160
2161
  // Empty sets are uninteresting.
2162
120k
  if (Previous.empty())
2163
113k
    return;
2164
2165
6.42k
  LookupResult::Filter Filter = Previous.makeFilter();
2166
12.8k
  while (Filter.hasNext()) {
2167
6.42k
    NamedDecl *Old = Filter.next();
2168
2169
    // Non-hidden declarations are never ignored.
2170
6.42k
    if (S.isVisible(Old))
2171
6.41k
      continue;
2172
2173
    // Declarations of the same entity are not ignored, even if they have
2174
    // different linkages.
2175
17
    if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2176
16
      if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2177
16
                                Decl->getUnderlyingType()))
2178
5
        continue;
2179
2180
      // If both declarations give a tag declaration a typedef name for linkage
2181
      // purposes, then they declare the same entity.
2182
11
      if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2183
11
          Decl->getAnonDeclWithTypedefName())
2184
11
        continue;
2185
1
    }
2186
2187
1
    Filter.erase();
2188
1
  }
2189
2190
6.42k
  Filter.done();
2191
6.42k
}
2192
2193
37.0k
bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2194
37.0k
  QualType OldType;
2195
37.0k
  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2196
6.10k
    OldType = OldTypedef->getUnderlyingType();
2197
30.9k
  else
2198
30.9k
    OldType = Context.getTypeDeclType(Old);
2199
37.0k
  QualType NewType = New->getUnderlyingType();
2200
2201
37.0k
  if (NewType->isVariablyModifiedType()) {
2202
    // Must not redefine a typedef with a variably-modified type.
2203
2
    int Kind = isa<TypeAliasDecl>(Old) ? 
10
: 0;
2204
2
    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2205
2
      << Kind << NewType;
2206
2
    if (Old->getLocation().isValid())
2207
2
      notePreviousDefinition(Old, New->getLocation());
2208
2
    New->setInvalidDecl();
2209
2
    return true;
2210
2
  }
2211
2212
37.0k
  if (OldType != NewType &&
2213
35.0k
      !OldType->isDependentType() &&
2214
34.9k
      !NewType->isDependentType() &&
2215
34.9k
      !Context.hasSameType(OldType, NewType)) {
2216
45
    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 
044
;
2217
89
    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2218
89
      << Kind << NewType << OldType;
2219
89
    if (Old->getLocation().isValid())
2220
84
      notePreviousDefinition(Old, New->getLocation());
2221
89
    New->setInvalidDecl();
2222
89
    return true;
2223
89
  }
2224
36.9k
  return false;
2225
36.9k
}
2226
2227
/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2228
/// same name and scope as a previous declaration 'Old'.  Figure out
2229
/// how to resolve this situation, merging decls or emitting
2230
/// diagnostics as appropriate. If there was an error, set New to be invalid.
2231
///
2232
void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2233
37.6k
                                LookupResult &OldDecls) {
2234
  // If the new decl is known invalid already, don't bother doing any
2235
  // merging checks.
2236
37.6k
  if (New->isInvalidDecl()) 
return10
;
2237
2238
  // Allow multiple definitions for ObjC built-in typedefs.
2239
  // FIXME: Verify the underlying types are equivalent!
2240
37.6k
  if (getLangOpts().ObjC) {
2241
26.8k
    const IdentifierInfo *TypeID = New->getIdentifier();
2242
26.8k
    switch (TypeID->getLength()) {
2243
25.6k
    default: break;
2244
344
    case 2:
2245
344
      {
2246
344
        if (!TypeID->isStr("id"))
2247
4
          break;
2248
340
        QualType T = New->getUnderlyingType();
2249
340
        if (!T->isPointerType())
2250
3
          break;
2251
337
        if (!T->isVoidPointerType()) {
2252
332
          QualType PT = T->castAs<PointerType>()->getPointeeType();
2253
332
          if (!PT->isStructureType())
2254
2
            break;
2255
335
        }
2256
335
        Context.setObjCIdRedefinitionType(T);
2257
        // Install the built-in type for 'id', ignoring the current definition.
2258
335
        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2259
335
        return;
2260
335
      }
2261
494
    case 5:
2262
494
      if (!TypeID->isStr("Class"))
2263
170
        break;
2264
324
      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2265
      // Install the built-in type for 'Class', ignoring the current definition.
2266
324
      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2267
324
      return;
2268
322
    case 3:
2269
322
      if (!TypeID->isStr("SEL"))
2270
2
        break;
2271
320
      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2272
      // Install the built-in type for 'SEL', ignoring the current definition.
2273
320
      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2274
320
      return;
2275
36.6k
    }
2276
    // Fall through - the typedef name was not a builtin type.
2277
26.8k
  }
2278
2279
  // Verify the old decl was also a type.
2280
36.6k
  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2281
36.6k
  if (!Old) {
2282
14
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2283
14
      << New->getDeclName();
2284
2285
14
    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2286
14
    if (OldD->getLocation().isValid())
2287
14
      notePreviousDefinition(OldD, New->getLocation());
2288
2289
14
    return New->setInvalidDecl();
2290
14
  }
2291
2292
  // If the old declaration is invalid, just give up here.
2293
36.6k
  if (Old->isInvalidDecl())
2294
12
    return New->setInvalidDecl();
2295
2296
36.6k
  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2297
5.67k
    auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2298
5.67k
    auto *NewTag = New->getAnonDeclWithTypedefName();
2299
5.67k
    NamedDecl *Hidden = nullptr;
2300
5.67k
    if (OldTag && 
NewTag18
&&
2301
12
        OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2302
12
        !hasVisibleDefinition(OldTag, &Hidden)) {
2303
      // There is a definition of this tag, but it is not visible. Use it
2304
      // instead of our tag.
2305
11
      New->setTypeForDecl(OldTD->getTypeForDecl());
2306
11
      if (OldTD->isModed())
2307
0
        New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2308
0
                                    OldTD->getUnderlyingType());
2309
11
      else
2310
11
        New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2311
2312
      // Make the old tag definition visible.
2313
11
      makeMergedDefinitionVisible(Hidden);
2314
2315
      // If this was an unscoped enumeration, yank all of its enumerators
2316
      // out of the scope.
2317
11
      if (isa<EnumDecl>(NewTag)) {
2318
5
        Scope *EnumScope = getNonFieldDeclScope(S);
2319
0
        for (auto *D : NewTag->decls()) {
2320
0
          auto *ED = cast<EnumConstantDecl>(D);
2321
0
          assert(EnumScope->isDeclScope(ED));
2322
0
          EnumScope->RemoveDecl(ED);
2323
0
          IdResolver.RemoveDecl(ED);
2324
0
          ED->getLexicalDeclContext()->removeDecl(ED);
2325
0
        }
2326
5
      }
2327
11
    }
2328
5.67k
  }
2329
2330
  // If the typedef types are not identical, reject them in all languages and
2331
  // with any extensions enabled.
2332
36.6k
  if (isIncompatibleTypedef(Old, New))
2333
54
    return;
2334
2335
  // The types match.  Link up the redeclaration chain and merge attributes if
2336
  // the old declaration was a typedef.
2337
36.6k
  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2338
5.61k
    New->setPreviousDecl(Typedef);
2339
5.61k
    mergeDeclAttributes(New, Old);
2340
5.61k
  }
2341
2342
36.6k
  if (getLangOpts().MicrosoftExt)
2343
41
    return;
2344
2345
36.5k
  if (getLangOpts().CPlusPlus) {
2346
    // C++ [dcl.typedef]p2:
2347
    //   In a given non-class scope, a typedef specifier can be used to
2348
    //   redefine the name of any type declared in that scope to refer
2349
    //   to the type to which it already refers.
2350
33.5k
    if (!isa<CXXRecordDecl>(CurContext))
2351
33.5k
      return;
2352
2353
    // C++0x [dcl.typedef]p4:
2354
    //   In a given class scope, a typedef specifier can be used to redefine
2355
    //   any class-name declared in that scope that is not also a typedef-name
2356
    //   to refer to the type to which it already refers.
2357
    //
2358
    // This wording came in via DR424, which was a correction to the
2359
    // wording in DR56, which accidentally banned code like:
2360
    //
2361
    //   struct S {
2362
    //     typedef struct A { } A;
2363
    //   };
2364
    //
2365
    // in the C++03 standard. We implement the C++0x semantics, which
2366
    // allow the above but disallow
2367
    //
2368
    //   struct S {
2369
    //     typedef int I;
2370
    //     typedef int I;
2371
    //   };
2372
    //
2373
    // since that was the intent of DR56.
2374
34
    if (!isa<TypedefNameDecl>(Old))
2375
12
      return;
2376
2377
22
    Diag(New->getLocation(), diag::err_redefinition)
2378
22
      << New->getDeclName();
2379
22
    notePreviousDefinition(Old, New->getLocation());
2380
22
    return New->setInvalidDecl();
2381
22
  }
2382
2383
  // Modules always permit redefinition of typedefs, as does C11.
2384
2.97k
  if (getLangOpts().Modules || 
getLangOpts().C11589
)
2385
2.94k
    return;
2386
2387
  // If we have a redefinition of a typedef in C, emit a warning.  This warning
2388
  // is normally mapped to an error, but can be controlled with
2389
  // -Wtypedef-redefinition.  If either the original or the redefinition is
2390
  // in a system header, don't emit this for compatibility with GCC.
2391
33
  if (getDiagnostics().getSuppressSystemWarnings() &&
2392
      // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2393
33
      (Old->isImplicit() ||
2394
32
       Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2395
14
       Context.getSourceManager().isInSystemHeader(New->getLocation())))
2396
19
    return;
2397
2398
14
  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2399
14
    << New->getDeclName();
2400
14
  notePreviousDefinition(Old, New->getLocation());
2401
14
}
2402
2403
/// DeclhasAttr - returns true if decl Declaration already has the target
2404
/// attribute.
2405
256k
static bool DeclHasAttr(const Decl *D, const Attr *A) {
2406
256k
  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2407
256k
  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2408
256k
  for (const auto *i : D->attrs())
2409
178k
    if (i->getKind() == A->getKind()) {
2410
26.7k
      if (Ann) {
2411
39
        if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2412
28
          return true;
2413
11
        continue;
2414
11
      }
2415
      // FIXME: Don't hardcode this check
2416
26.6k
      if (OA && 
isa<OwnershipAttr>(i)0
)
2417
0
        return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2418
26.6k
      return true;
2419
26.6k
    }
2420
2421
230k
  return false;
2422
256k
}
2423
2424
10
static bool isAttributeTargetADefinition(Decl *D) {
2425
10
  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2426
5
    return VD->isThisDeclarationADefinition();
2427
5
  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2428
5
    return TD->isCompleteDefinition() || TD->isBeingDefined();
2429
0
  return true;
2430
0
}
2431
2432
/// Merge alignment attributes from \p Old to \p New, taking into account the
2433
/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2434
///
2435
/// \return \c true if any attributes were added to \p New.
2436
335k
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2437
  // Look for alignas attributes on Old, and pick out whichever attribute
2438
  // specifies the strictest alignment requirement.
2439
335k
  AlignedAttr *OldAlignasAttr = nullptr;
2440
335k
  AlignedAttr *OldStrictestAlignAttr = nullptr;
2441
335k
  unsigned OldAlign = 0;
2442
68
  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2443
    // FIXME: We have no way of representing inherited dependent alignments
2444
    // in a case like:
2445
    //   template<int A, int B> struct alignas(A) X;
2446
    //   template<int A, int B> struct alignas(B) X {};
2447
    // For now, we just ignore any alignas attributes which are not on the
2448
    // definition in such a case.
2449
68
    if (I->isAlignmentDependent())
2450
3
      return false;
2451
2452
65
    if (I->isAlignas())
2453
21
      OldAlignasAttr = I;
2454
2455
65
    unsigned Align = I->getAlignment(S.Context);
2456
65
    if (Align > OldAlign) {
2457
64
      OldAlign = Align;
2458
64
      OldStrictestAlignAttr = I;
2459
64
    }
2460
65
  }
2461
2462
  // Look for alignas attributes on New.
2463
335k
  AlignedAttr *NewAlignasAttr = nullptr;
2464
335k
  unsigned NewAlign = 0;
2465
49
  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2466
49
    if (I->isAlignmentDependent())
2467
0
      return false;
2468
2469
49
    if (I->isAlignas())
2470
11
      NewAlignasAttr = I;
2471
2472
49
    unsigned Align = I->getAlignment(S.Context);
2473
49
    if (Align > NewAlign)
2474
48
      NewAlign = Align;
2475
49
  }
2476
2477
335k
  if (OldAlignasAttr && 
NewAlignasAttr19
&&
OldAlign != NewAlign9
) {
2478
    // Both declarations have 'alignas' attributes. We require them to match.
2479
    // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2480
    // fall short. (If two declarations both have alignas, they must both match
2481
    // every definition, and so must match each other if there is a definition.)
2482
2483
    // If either declaration only contains 'alignas(0)' specifiers, then it
2484
    // specifies the natural alignment for the type.
2485
7
    if (OldAlign == 0 || NewAlign == 0) {
2486
0
      QualType Ty;
2487
0
      if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2488
0
        Ty = VD->getType();
2489
0
      else
2490
0
        Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2491
2492
0
      if (OldAlign == 0)
2493
0
        OldAlign = S.Context.getTypeAlign(Ty);
2494
0
      if (NewAlign == 0)
2495
0
        NewAlign = S.Context.getTypeAlign(Ty);
2496
0
    }
2497
2498
7
    if (OldAlign != NewAlign) {
2499
7
      S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2500
7
        << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2501
7
        << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2502
7
      S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2503
7
    }
2504
7
  }
2505
2506
335k
  if (OldAlignasAttr && 
!NewAlignasAttr19
&&
isAttributeTargetADefinition(New)10
) {
2507
    // C++11 [dcl.align]p6:
2508
    //   if any declaration of an entity has an alignment-specifier,
2509
    //   every defining declaration of that entity shall specify an
2510
    //   equivalent alignment.
2511
    // C11 6.7.5/7:
2512
    //   If the definition of an object does not have an alignment
2513
    //   specifier, any other declaration of that object shall also
2514
    //   have no alignment specifier.
2515
3
    S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2516
3
      << OldAlignasAttr;
2517
3
    S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2518
3
      << OldAlignasAttr;
2519
3
  }
2520
2521
335k
  bool AnyAdded = false;
2522
2523
  // Ensure we have an attribute representing the strictest alignment.
2524
335k
  if (OldAlign > NewAlign) {
2525
52
    AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2526
52
    Clone->setInherited(true);
2527
52
    New->addAttr(Clone);
2528
52
    AnyAdded = true;
2529
52
  }
2530
2531
  // Ensure we have an alignas attribute if the old declaration had one.
2532
335k
  if (OldAlignasAttr && 
!NewAlignasAttr19
&&
2533
10
      !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2534
0
    AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2535
0
    Clone->setInherited(true);
2536
0
    New->addAttr(Clone);
2537
0
    AnyAdded = true;
2538
0
  }
2539
2540
335k
  return AnyAdded;
2541
335k
}
2542
2543
static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2544
                               const InheritableAttr *Attr,
2545
614k
                               Sema::AvailabilityMergeKind AMK) {
2546
  // This function copies an attribute Attr from a previous declaration to the
2547
  // new declaration D if the new declaration doesn't itself have that attribute
2548
  // yet or if that attribute allows duplicates.
2549
  // If you're adding a new attribute that requires logic different from
2550
  // "use explicit attribute on decl if present, else use attribute from
2551
  // previous decl", for example if the attribute needs to be consistent
2552
  // between redeclarations, you need to call a custom merge function here.
2553
614k
  InheritableAttr *NewAttr = nullptr;
2554
614k
  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2555
219k
    NewAttr = S.mergeAvailabilityAttr(
2556
219k
        D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2557
219k
        AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2558
219k
        AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2559
219k
        AA->getPriority());
2560
394k
  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2561
104k
    NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2562
290k
  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2563
17.3k
    NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2564
272k
  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2565
1.47k
    NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2566
271k
  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2567
1.34k
    NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2568
269k
  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2569
909
    NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2570
909
                                FA->getFirstArg());
2571
269k
  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2572
28
    NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2573
268k
  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2574
17
    NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2575
268k
  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2576
33
    NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2577
33
                                       IA->getInheritanceModel());
2578
268k
  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2579
7.95k
    NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2580
7.95k
                                      &S.Context.Idents.get(AA->getSpelling()));
2581
260k
  else if (S.getLangOpts().CUDA && 
isa<FunctionDecl>(D)88
&&
2582
65
           (isa<CUDAHostAttr>(Attr) || 
isa<CUDADeviceAttr>(Attr)36
||
2583
62
            
isa<CUDAGlobalAttr>(Attr)3
)) {
2584
    // CUDA target attributes are part of function signature for
2585
    // overloading purposes and must not be merged.
2586
62
    return false;
2587
260k
  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2588
3
    NewAttr = S.mergeMinSizeAttr(D, *MA);
2589
260k
  else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2590
13
    NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2591
260k
  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2592
12
    NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2593
260k
  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2594
8
    NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2595
260k
  else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2596
1
    NewAttr = S.mergeCommonAttr(D, *CommonA);
2597
260k
  else if (isa<AlignedAttr>(Attr))
2598
    // AlignedAttrs are handled separately, because we need to handle all
2599
    // such attributes on a declaration at the same time.
2600
70
    NewAttr = nullptr;
2601
260k
  else if ((isa<DeprecatedAttr>(Attr) || 
isa<UnavailableAttr>(Attr)260k
) &&
2602
222
           (AMK == Sema::AMK_Override ||
2603
154
            AMK == Sema::AMK_ProtocolImplementation))
2604
83
    NewAttr = nullptr;
2605
260k
  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2606
37
    NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2607
260k
  else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2608
1
    NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2609
260k
  else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2610
1
    NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2611
260k
  else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2612
7
    NewAttr = S.mergeImportModuleAttr(D, *IMA);
2613
260k
  else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2614
7
    NewAttr = S.mergeImportNameAttr(D, *INA);
2615
260k
  else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2616
12
    NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2617
260k
  else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2618
3
    NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2619
260k
  else if (Attr->shouldInheritEvenIfAlreadyPresent() || 
!DeclHasAttr(D, Attr)256k
)
2620
234k
    NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2621
2622
614k
  if (NewAttr) {
2623
361k
    NewAttr->setInherited(true);
2624
361k
    D->addAttr(NewAttr);
2625
361k
    if (isa<MSInheritanceAttr>(NewAttr))
2626
30
      S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2627
361k
    return true;
2628
361k
  }
2629
2630
252k
  return false;
2631
252k
}
2632
2633
155k
static const NamedDecl *getDefinition(const Decl *D) {
2634
155k
  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2635
27.7k
    return TD->getDefinition();
2636
127k
  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2637
1.05k
    const VarDecl *Def = VD->getDefinition();
2638
1.05k
    if (Def)
2639
44
      return Def;
2640
1.00k
    return VD->getActingDefinition();
2641
1.00k
  }
2642
126k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2643
41.2k
    const FunctionDecl *Def = nullptr;
2644
41.2k
    if (FD->isDefined(Def, true))
2645
271
      return Def;
2646
126k
  }
2647
126k
  return nullptr;
2648
126k
}
2649
2650
1.92k
static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2651
1.92k
  for (const auto *Attribute : D->attrs())
2652
2.25k
    if (Attribute->getKind() == Kind)
2653
1.88k
      return true;
2654
41
  return false;
2655
1.92k
}
2656
2657
/// checkNewAttributesAfterDef - If we already have a definition, check that
2658
/// there are no new attributes in this declaration.
2659
363k
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2660
363k
  if (!New->hasAttrs())
2661
208k
    return;
2662
2663
155k
  const NamedDecl *Def = getDefinition(Old);
2664
155k
  if (!Def || 
Def == New12.1k
)
2665
153k
    return;
2666
2667
1.89k
  AttrVec &NewAttributes = New->getAttrs();
2668
3.85k
  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2669
1.95k
    const Attr *NewAttribute = NewAttributes[I];
2670
2671
1.95k
    if (isa<AliasAttr>(NewAttribute) || 
isa<IFuncAttr>(NewAttribute)1.94k
) {
2672
5
      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2673
4
        Sema::SkipBodyInfo SkipBody;
2674
4
        S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2675
2676
        // If we're skipping this definition, drop the "alias" attribute.
2677
4
        if (SkipBody.ShouldSkip) {
2678
0
          NewAttributes.erase(NewAttributes.begin() + I);
2679
0
          --E;
2680
0
          continue;
2681
0
        }
2682
1
      } else {
2683
1
        VarDecl *VD = cast<VarDecl>(New);
2684
1
        unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2685
1
                                VarDecl::TentativeDefinition
2686
1
                            ? diag::err_alias_after_tentative
2687
0
                            : diag::err_redefinition;
2688
1
        S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2689
1
        if (Diag == diag::err_redefinition)
2690
0
          S.notePreviousDefinition(Def, VD->getLocation());
2691
1
        else
2692
1
          S.Diag(Def->getLocation(), diag::note_previous_definition);
2693
1
        VD->setInvalidDecl();
2694
1
      }
2695
5
      ++I;
2696
5
      continue;
2697
1.94k
    }
2698
2699
1.94k
    if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2700
      // Tentative definitions are only interesting for the alias check above.
2701
66
      if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2702
19
        ++I;
2703
19
        continue;
2704
19
      }
2705
1.92k
    }
2706
2707
1.92k
    if (hasAttribute(Def, NewAttribute->getKind())) {
2708
1.88k
      ++I;
2709
1.88k
      continue; // regular attr merging will take care of validating this.
2710
1.88k
    }
2711
2712
41
    if (isa<C11NoReturnAttr>(NewAttribute)) {
2713
      // C's _Noreturn is allowed to be added to a function after it is defined.
2714
1
      ++I;
2715
1
      continue;
2716
40
    } else if (isa<UuidAttr>(NewAttribute)) {
2717
      // msvc will allow a subsequent definition to add an uuid to a class
2718
2
      ++I;
2719
2
      continue;
2720
38
    } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2721
4
      if (AA->isAlignas()) {
2722
        // C++11 [dcl.align]p6:
2723
        //   if any declaration of an entity has an alignment-specifier,
2724
        //   every defining declaration of that entity shall specify an
2725
        //   equivalent alignment.
2726
        // C11 6.7.5/7:
2727
        //   If the definition of an object does not have an alignment
2728
        //   specifier, any other declaration of that object shall also
2729
        //   have no alignment specifier.
2730
4
        S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2731
4
          << AA;
2732
4
        S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2733
4
          << AA;
2734
4
        NewAttributes.erase(NewAttributes.begin() + I);
2735
4
        --E;
2736
4
        continue;
2737
4
      }
2738
34
    } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2739
      // If there is a C definition followed by a redeclaration with this
2740
      // attribute then there are two different definitions. In C++, prefer the
2741
      // standard diagnostics.
2742
2
      if (!S.getLangOpts().CPlusPlus) {
2743
1
        S.Diag(NewAttribute->getLocation(),
2744
1
               diag::err_loader_uninitialized_redeclaration);
2745
1
        S.Diag(Def->getLocation(), diag::note_previous_definition);
2746
1
        NewAttributes.erase(NewAttributes.begin() + I);
2747
1
        --E;
2748
1
        continue;
2749
1
      }
2750
32
    } else if (isa<SelectAnyAttr>(NewAttribute) &&
2751
8
               cast<VarDecl>(New)->isInline() &&
2752
2
               !cast<VarDecl>(New)->isInlineSpecified()) {
2753
      // Don't warn about applying selectany to implicitly inline variables.
2754
      // Older compilers and language modes would require the use of selectany
2755
      // to make such variables inline, and it would have no effect if we
2756
      // honored it.
2757
2
      ++I;
2758
2
      continue;
2759
30
    } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2760
      // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2761
      // declarations after defintions.
2762
0
      ++I;
2763
0
      continue;
2764
0
    }
2765
2766
31
    S.Diag(NewAttribute->getLocation(),
2767
31
           diag::warn_attribute_precede_definition);
2768
31
    S.Diag(Def->getLocation(), diag::note_previous_definition);
2769
31
    NewAttributes.erase(NewAttributes.begin() + I);
2770
31
    --E;
2771
31
  }
2772
1.89k
}
2773
2774
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2775
                                     const ConstInitAttr *CIAttr,
2776
26
                                     bool AttrBeforeInit) {
2777
26
  SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2778
2779
  // Figure out a good way to write this specifier on the old declaration.
2780
  // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2781
  // enough of the attribute list spelling information to extract that without
2782
  // heroics.
2783
26
  std::string SuitableSpelling;
2784
26
  if (S.getLangOpts().CPlusPlus20)
2785
20
    SuitableSpelling = std::string(
2786
20
        S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2787
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus1124
)
2788
22
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2789
22
        InsertLoc, {tok::l_square, tok::l_square,
2790
22
                    S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2791
22
                    S.PP.getIdentifierInfo("require_constant_initialization"),
2792
22
                    tok::r_square, tok::r_square}));
2793
26
  if (SuitableSpelling.empty())
2794
20
    SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2795
20
        InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2796
20
                    S.PP.getIdentifierInfo("require_constant_initialization"),
2797
20
                    tok::r_paren, tok::r_paren}));
2798
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus2020
)
2799
14
    SuitableSpelling = "constinit";
2800
26
  if (SuitableSpelling.empty() && 
S.getLangOpts().CPlusPlus116
)
2801
4
    SuitableSpelling = "[[clang::require_constant_initialization]]";
2802
26
  if (SuitableSpelling.empty())
2803
2
    SuitableSpelling = "__attribute__((require_constant_initialization))";
2804
26
  SuitableSpelling += " ";
2805
2806
26
  if (AttrBeforeInit) {
2807
    // extern constinit int a;
2808
    // int a = 0; // error (missing 'constinit'), accepted as extension
2809
14
    assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2810
14
    S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2811
14
        << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2812
14
    S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2813
12
  } else {
2814
    // int a = 0;
2815
    // constinit extern int a; // error (missing 'constinit')
2816
12
    S.Diag(CIAttr->getLocation(),
2817
6
           CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2818
6
                                 : diag::warn_require_const_init_added_too_late)
2819
12
        << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2820
12
    S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2821
12
        << CIAttr->isConstinit()
2822
12
        << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2823
12
  }
2824
26
}
2825
2826
/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2827
void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2828
806k
                               AvailabilityMergeKind AMK) {
2829
806k
  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2830
211
    UsedAttr *NewAttr = OldAttr->clone(Context);
2831
211
    NewAttr->setInherited(true);
2832
211
    New->addAttr(NewAttr);
2833
211
  }
2834
2835
806k
  if (!Old->hasAttrs() && 
!New->hasAttrs()471k
)
2836
442k
    return;
2837
2838
  // [dcl.constinit]p1:
2839
  //   If the [constinit] specifier is applied to any declaration of a
2840
  //   variable, it shall be applied to the initializing declaration.
2841
363k
  const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2842
363k
  const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2843
363k
  if (bool(OldConstInit) != bool(NewConstInit)) {
2844
51
    const auto *OldVD = cast<VarDecl>(Old);
2845
51
    auto *NewVD = cast<VarDecl>(New);
2846
2847
    // Find the initializing declaration. Note that we might not have linked
2848
    // the new declaration into the redeclaration chain yet.
2849
51
    const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2850
51
    if (!InitDecl &&
2851
37
        (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2852
37
      InitDecl = NewVD;
2853
2854
51
    if (InitDecl == NewVD) {
2855
      // This is the initializing declaration. If it would inherit 'constinit',
2856
      // that's ill-formed. (Note that we do not apply this to the attribute
2857
      // form).
2858
37
      if (OldConstInit && 
OldConstInit->isConstinit()36
)
2859
14
        diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2860
14
                                 /*AttrBeforeInit=*/true);
2861
14
    } else if (NewConstInit) {
2862
      // This is the first time we've been told that this declaration should
2863
      // have a constant initializer. If we already saw the initializing
2864
      // declaration, this is too late.
2865
12
      if (InitDecl && InitDecl != NewVD) {
2866
12
        diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2867
12
                                 /*AttrBeforeInit=*/false);
2868
12
        NewVD->dropAttr<ConstInitAttr>();
2869
12
      }
2870
12
    }
2871
51
  }
2872
2873
  // Attributes declared post-definition are currently ignored.
2874
363k
  checkNewAttributesAfterDef(*this, New, Old);
2875
2876
363k
  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2877
750
    if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2878
645
      if (!OldA->isEquivalent(NewA)) {
2879
        // This redeclaration changes __asm__ label.
2880
2
        Diag(New->getLocation(), diag::err_different_asm_label);
2881
2
        Diag(OldA->getLocation(), diag::note_previous_declaration);
2882
2
      }
2883
105
    } else if (Old->isUsed()) {
2884
      // This redeclaration adds an __asm__ label to a declaration that has
2885
      // already been ODR-used.
2886
2
      Diag(New->getLocation(), diag::err_late_asm_label_name)
2887
2
        << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2888
2
    }
2889
750
  }
2890
2891
  // Re-declaration cannot add abi_tag's.
2892
363k
  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2893
3
    if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2894
4
      for (const auto &NewTag : NewAbiTagAttr->tags()) {
2895
4
        if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2896
1
                      NewTag) == OldAbiTagAttr->tags_end()) {
2897
1
          Diag(NewAbiTagAttr->getLocation(),
2898
1
               diag::err_new_abi_tag_on_redeclaration)
2899
1
              << NewTag;
2900
1
          Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2901
1
        }
2902
4
      }
2903
1
    } else {
2904
1
      Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2905
1
      Diag(Old->getLocation(), diag::note_previous_declaration);
2906
1
    }
2907
3
  }
2908
2909
  // This redeclaration adds a section attribute.
2910
363k
  if (New->hasAttr<SectionAttr>() && 
!Old->hasAttr<SectionAttr>()24
) {
2911
16
    if (auto *VD = dyn_cast<VarDecl>(New)) {
2912
6
      if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2913
2
        Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2914
2
        Diag(Old->getLocation(), diag::note_previous_declaration);
2915
2
      }
2916
6
    }
2917
16
  }
2918
2919
  // Redeclaration adds code-seg attribute.
2920
363k
  const auto *NewCSA = New->getAttr<CodeSegAttr>();
2921
363k
  if (NewCSA && 
!Old->hasAttr<CodeSegAttr>()16
&&
2922
1
      !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2923
1
    Diag(New->getLocation(), diag::warn_mismatched_section)
2924
1
         << 0 /*codeseg*/;
2925
1
    Diag(Old->getLocation(), diag::note_previous_declaration);
2926
1
  }
2927
2928
363k
  if (!Old->hasAttrs())
2929
28.1k
    return;
2930
2931
335k
  bool foundAny = New->hasAttrs();
2932
2933
  // Ensure that any moving of objects within the allocated map is done before
2934
  // we process them.
2935
335k
  if (!foundAny) 
New->setAttrs(AttrVec())208k
;
2936
2937
614k
  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2938
    // Ignore deprecated/unavailable/availability attributes if requested.
2939
614k
    AvailabilityMergeKind LocalAMK = AMK_None;
2940
614k
    if (isa<DeprecatedAttr>(I) ||
2941
614k
        isa<UnavailableAttr>(I) ||
2942
614k
        isa<AvailabilityAttr>(I)) {
2943
220k
      switch (AMK) {
2944
0
      case AMK_None:
2945
0
        continue;
2946
2947
41.7k
      case AMK_Redeclaration:
2948
218k
      case AMK_Override:
2949
220k
      case AMK_ProtocolImplementation:
2950
220k
        LocalAMK = AMK;
2951
220k
        break;
2952
614k
      }
2953
614k
    }
2954
2955
    // Already handled.
2956
614k
    if (isa<UsedAttr>(I))
2957
210
      continue;
2958
2959
614k
    if (mergeDeclAttribute(*this, New, I, LocalAMK))
2960
361k
      foundAny = true;
2961
614k
  }
2962
2963
335k
  if (mergeAlignedAttrs(*this, New, Old))
2964
52
    foundAny = true;
2965
2966
335k
  if (!foundAny) 
New->dropAttrs()5.91k
;
2967
335k
}
2968
2969
/// mergeParamDeclAttributes - Copy attributes from the old parameter
2970
/// to the new one.
2971
static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2972
                                     const ParmVarDecl *oldDecl,
2973
508k
                                     Sema &S) {
2974
  // C++11 [dcl.attr.depend]p2:
2975
  //   The first declaration of a function shall specify the
2976
  //   carries_dependency attribute for its declarator-id if any declaration
2977
  //   of the function specifies the carries_dependency attribute.
2978
508k
  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2979
508k
  if (CDA && 
!oldDecl->hasAttr<CarriesDependencyAttr>()2
) {
2980
1
    S.Diag(CDA->getLocation(),
2981
1
           diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2982
    // Find the first declaration of the parameter.
2983
    // FIXME: Should we build redeclaration chains for function parameters?
2984
1
    const FunctionDecl *FirstFD =
2985
1
      cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2986
1
    const ParmVarDecl *FirstVD =
2987
1
      FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2988
1
    S.Diag(FirstVD->getLocation(),
2989
1
           diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2990
1
  }
2991
2992
508k
  if (!oldDecl->hasAttrs())
2993
502k
    return;
2994
2995
6.26k
  bool foundAny = newDecl->hasAttrs();
2996
2997
  // Ensure that any moving of objects within the allocated map is
2998
  // done before we process them.
2999
6.26k
  if (!foundAny) 
newDecl->setAttrs(AttrVec())19
;
3000
3001
321
  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3002
321
    if (!DeclHasAttr(newDecl, I)) {
3003
15
      InheritableAttr *newAttr =
3004
15
        cast<InheritableParamAttr>(I->clone(S.Context));
3005
15
      newAttr->setInherited(true);
3006
15
      newDecl->addAttr(newAttr);
3007
15
      foundAny = true;
3008
15
    }
3009
321
  }
3010
3011
6.26k
  if (!foundAny) 
newDecl->dropAttrs()6
;
3012
6.26k
}
3013
3014
static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3015
                                const ParmVarDecl *OldParam,
3016
390k
                                Sema &S) {
3017
390k
  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3018
2.08k
    if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3019
1.63k
      if (*Oldnullability != *Newnullability) {
3020
2
        S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3021
2
          << DiagNullabilityKind(
3022
2
               *Newnullability,
3023
2
               ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3024
2
                != 0))
3025
2
          << DiagNullabilityKind(
3026
2
               *Oldnullability,
3027
2
               ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3028
2
                != 0));
3029
2
        S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3030
2
      }
3031
451
    } else {
3032
451
      QualType NewT = NewParam->getType();
3033
451
      NewT = S.Context.getAttributedType(
3034
451
                         AttributedType::getNullabilityAttrKind(*Oldnullability),
3035
451
                         NewT, NewT);
3036
451
      NewParam->setType(NewT);
3037
451
    }
3038
2.08k
  }
3039
390k
}
3040
3041
namespace {
3042
3043
/// Used in MergeFunctionDecl to keep track of function parameters in
3044
/// C.
3045
struct GNUCompatibleParamWarning {
3046
  ParmVarDecl *OldParm;
3047
  ParmVarDecl *NewParm;
3048
  QualType PromotedType;
3049
};
3050
3051
} // end anonymous namespace
3052
3053
// Determine whether the previous declaration was a definition, implicit
3054
// declaration, or a declaration.
3055
template <typename T>
3056
static std::pair<diag::kind, SourceLocation>
3057
304k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3058
304k
  diag::kind PrevDiag;
3059
304k
  SourceLocation OldLocation = Old->getLocation();
3060
304k
  if (Old->isThisDeclarationADefinition())
3061
12.6k
    PrevDiag = diag::note_previous_definition;
3062
292k
  else if (Old->isImplicit()) {
3063
13.6k
    PrevDiag = diag::note_previous_implicit_declaration;
3064
13.6k
    if (OldLocation.isInvalid())
3065
2.29k
      OldLocation = New->getLocation();
3066
13.6k
  } else
3067
278k
    PrevDiag = diag::note_previous_declaration;
3068
304k
  return std::make_pair(PrevDiag, OldLocation);
3069
304k
}
SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
Line
Count
Source
3057
245k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3058
245k
  diag::kind PrevDiag;
3059
245k
  SourceLocation OldLocation = Old->getLocation();
3060
245k
  if (Old->isThisDeclarationADefinition())
3061
11.1k
    PrevDiag = diag::note_previous_definition;
3062
234k
  else if (Old->isImplicit()) {
3063
13.6k
    PrevDiag = diag::note_previous_implicit_declaration;
3064
13.6k
    if (OldLocation.isInvalid())
3065
2.29k
      OldLocation = New->getLocation();
3066
13.6k
  } else
3067
220k
    PrevDiag = diag::note_previous_declaration;
3068
245k
  return std::make_pair(PrevDiag, OldLocation);
3069
245k
}
SemaDecl.cpp:std::__1::pair<unsigned int, clang::SourceLocation> getNoteDiagForInvalidRedeclaration<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3057
59.1k
getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3058
59.1k
  diag::kind PrevDiag;
3059
59.1k
  SourceLocation OldLocation = Old->getLocation();
3060
59.1k
  if (Old->isThisDeclarationADefinition())
3061
1.49k
    PrevDiag = diag::note_previous_definition;
3062
57.6k
  else if (Old->isImplicit()) {
3063
0
    PrevDiag = diag::note_previous_implicit_declaration;
3064
0
    if (OldLocation.isInvalid())
3065
0
      OldLocation = New->getLocation();
3066
0
  } else
3067
57.6k
    PrevDiag = diag::note_previous_declaration;
3068
59.1k
  return std::make_pair(PrevDiag, OldLocation);
3069
59.1k
}
3070
3071
/// canRedefineFunction - checks if a function can be redefined. Currently,
3072
/// only extern inline functions can be redefined, and even then only in
3073
/// GNU89 mode.
3074
static bool canRedefineFunction(const FunctionDecl *FD,
3075
529
                                const LangOptions& LangOpts) {
3076
529
  return ((FD->hasAttr<GNUInlineAttr>() || 
LangOpts.GNUInline525
) &&
3077
17
          !LangOpts.CPlusPlus &&
3078
17
          FD->isInlineSpecified() &&
3079
15
          FD->getStorageClass() == SC_Extern);
3080
529
}
3081
3082
1.15k
const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3083
1.15k
  const AttributedType *AT = T->getAs<AttributedType>();
3084
1.15k
  while (AT && 
!AT->isCallingConv()151
)
3085
0
    AT = AT->getModifiedType()->getAs<AttributedType>();
3086
1.15k
  return AT;
3087
1.15k
}
3088
3089
template <typename T>
3090
281k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3091
281k
  const DeclContext *DC = Old->getDeclContext();
3092
281k
  if (DC->isRecord())
3093
213k
    return false;
3094
3095
67.8k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3096
67.8k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()53.2k
)
3097
24
    return true;
3098
67.8k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()13.4k
)
3099
17
    return true;
3100
67.8k
  return false;
3101
67.8k
}
SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::FunctionDecl>(clang::FunctionDecl const*, clang::FunctionDecl const*)
Line
Count
Source
3090
222k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3091
222k
  const DeclContext *DC = Old->getDeclContext();
3092
222k
  if (DC->isRecord())
3093
157k
    return false;
3094
3095
64.9k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3096
64.9k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()51.8k
)
3097
21
    return true;
3098
64.9k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()11.9k
)
3099
17
    return true;
3100
64.9k
  return false;
3101
64.9k
}
SemaDecl.cpp:bool haveIncompatibleLanguageLinkages<clang::VarDecl>(clang::VarDecl const*, clang::VarDecl const*)
Line
Count
Source
3090
58.8k
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3091
58.8k
  const DeclContext *DC = Old->getDeclContext();
3092
58.8k
  if (DC->isRecord())
3093
55.8k
    return false;
3094
3095
2.93k
  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3096
2.93k
  if (OldLinkage == CXXLanguageLinkage && 
New->isInExternCContext()1.40k
)
3097
3
    return true;
3098
2.92k
  if (OldLinkage == CLanguageLinkage && 
New->isInExternCXXContext()1.40k
)
3099
0
    return true;
3100
2.92k
  return false;
3101
2.92k
}
3102
3103
24
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
SemaDecl.cpp:bool isExternC<clang::FunctionDecl>(clang::FunctionDecl*)
Line
Count
Source
3103
17
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
SemaDecl.cpp:bool isExternC<clang::VarDecl>(clang::VarDecl*)
Line
Count
Source
3103
7
template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3104
2
static bool isExternC(VarTemplateDecl *) { return false; }
3105
3106
/// Check whether a redeclaration of an entity introduced by a
3107
/// using-declaration is valid, given that we know it's not an overload
3108
/// (nor a hidden tag declaration).
3109
template<typename ExpectedDecl>
3110
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3111
39
                                   ExpectedDecl *New) {
3112
  // C++11 [basic.scope.declarative]p4:
3113
  //   Given a set of declarations in a single declarative region, each of
3114
  //   which specifies the same unqualified name,
3115
  //   -- they shall all refer to the same entity, or all refer to functions
3116
  //      and function templates; or
3117
  //   -- exactly one declaration shall declare a class name or enumeration
3118
  //      name that is not a typedef name and the other declarations shall all
3119
  //      refer to the same variable or enumerator, or all refer to functions
3120
  //      and function templates; in this case the class name or enumeration
3121
  //      name is hidden (3.3.10).
3122
3123
  // C++11 [namespace.udecl]p14:
3124
  //   If a function declaration in namespace scope or block scope has the
3125
  //   same name and the same parameter-type-list as a function introduced
3126
  //   by a using-declaration, and the declarations do not declare the same
3127
  //   function, the program is ill-formed.
3128
3129
39
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3130
39
  if (Old &&
3131
32
      !Old->getDeclContext()->getRedeclContext()->Equals(
3132
32
          New->getDeclContext()->getRedeclContext()) &&
3133
22
      !(isExternC(Old) && 
isExternC(New)4
))
3134
18
    Old = nullptr;
3135
3136
39
  if (!Old) {
3137
25
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3138
25
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3139
25
    S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3140
25
    return true;
3141
25
  }
3142
14
  return false;
3143
14
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::FunctionDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::FunctionDecl*)
Line
Count
Source
3111
28
                                   ExpectedDecl *New) {
3112
  // C++11 [basic.scope.declarative]p4:
3113
  //   Given a set of declarations in a single declarative region, each of
3114
  //   which specifies the same unqualified name,
3115
  //   -- they shall all refer to the same entity, or all refer to functions
3116
  //      and function templates; or
3117
  //   -- exactly one declaration shall declare a class name or enumeration
3118
  //      name that is not a typedef name and the other declarations shall all
3119
  //      refer to the same variable or enumerator, or all refer to functions
3120
  //      and function templates; in this case the class name or enumeration
3121
  //      name is hidden (3.3.10).
3122
3123
  // C++11 [namespace.udecl]p14:
3124
  //   If a function declaration in namespace scope or block scope has the
3125
  //   same name and the same parameter-type-list as a function introduced
3126
  //   by a using-declaration, and the declarations do not declare the same
3127
  //   function, the program is ill-formed.
3128
3129
28
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3130
28
  if (Old &&
3131
21
      !Old->getDeclContext()->getRedeclContext()->Equals(
3132
21
          New->getDeclContext()->getRedeclContext()) &&
3133
13
      !(isExternC(Old) && 
isExternC(New)4
))
3134
9
    Old = nullptr;
3135
3136
28
  if (!Old) {
3137
16
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3138
16
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3139
16
    S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3140
16
    return true;
3141
16
  }
3142
12
  return false;
3143
12
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarTemplateDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarTemplateDecl*)
Line
Count
Source
3111
3
                                   ExpectedDecl *New) {
3112
  // C++11 [basic.scope.declarative]p4:
3113
  //   Given a set of declarations in a single declarative region, each of
3114
  //   which specifies the same unqualified name,
3115
  //   -- they shall all refer to the same entity, or all refer to functions
3116
  //      and function templates; or
3117
  //   -- exactly one declaration shall declare a class name or enumeration
3118
  //      name that is not a typedef name and the other declarations shall all
3119
  //      refer to the same variable or enumerator, or all refer to functions
3120
  //      and function templates; in this case the class name or enumeration
3121
  //      name is hidden (3.3.10).
3122
3123
  // C++11 [namespace.udecl]p14:
3124
  //   If a function declaration in namespace scope or block scope has the
3125
  //   same name and the same parameter-type-list as a function introduced
3126
  //   by a using-declaration, and the declarations do not declare the same
3127
  //   function, the program is ill-formed.
3128
3129
3
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3130
3
  if (Old &&
3131
3
      !Old->getDeclContext()->getRedeclContext()->Equals(
3132
3
          New->getDeclContext()->getRedeclContext()) &&
3133
2
      !(isExternC(Old) && 
isExternC(New)0
))
3134
2
    Old = nullptr;
3135
3136
3
  if (!Old) {
3137
2
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3138
2
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3139
2
    S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3140
2
    return true;
3141
2
  }
3142
1
  return false;
3143
1
}
SemaDecl.cpp:bool checkUsingShadowRedecl<clang::VarDecl>(clang::Sema&, clang::UsingShadowDecl*, clang::VarDecl*)
Line
Count
Source
3111
8
                                   ExpectedDecl *New) {
3112
  // C++11 [basic.scope.declarative]p4:
3113
  //   Given a set of declarations in a single declarative region, each of
3114
  //   which specifies the same unqualified name,
3115
  //   -- they shall all refer to the same entity, or all refer to functions
3116
  //      and function templates; or
3117
  //   -- exactly one declaration shall declare a class name or enumeration
3118
  //      name that is not a typedef name and the other declarations shall all
3119
  //      refer to the same variable or enumerator, or all refer to functions
3120
  //      and function templates; in this case the class name or enumeration
3121
  //      name is hidden (3.3.10).
3122
3123
  // C++11 [namespace.udecl]p14:
3124
  //   If a function declaration in namespace scope or block scope has the
3125
  //   same name and the same parameter-type-list as a function introduced
3126
  //   by a using-declaration, and the declarations do not declare the same
3127
  //   function, the program is ill-formed.
3128
3129
8
  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3130
8
  if (Old &&
3131
8
      !Old->getDeclContext()->getRedeclContext()->Equals(
3132
8
          New->getDeclContext()->getRedeclContext()) &&
3133
7
      !(isExternC(Old) && 
isExternC(New)0
))
3134
7
    Old = nullptr;
3135
3136
8
  if (!Old) {
3137
7
    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3138
7
    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3139
7
    S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3140
7
    return true;
3141
7
  }
3142
1
  return false;
3143
1
}
3144
3145
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3146
201k
                                            const FunctionDecl *B) {
3147
201k
  assert(A->getNumParams() == B->getNumParams());
3148
3149
390k
  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3150
390k
    const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3151
390k
    const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3152
390k
    if (AttrA == AttrB)
3153
390k
      return true;
3154
7
    return AttrA && AttrB && 
AttrA->getType() == AttrB->getType()6
&&
3155
2
           AttrA->isDynamic() == AttrB->isDynamic();
3156
7
  };
3157
3158
201k
  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3159
201k
}
3160
3161
/// If necessary, adjust the semantic declaration context for a qualified
3162
/// declaration to name the correct inline namespace within the qualifier.
3163
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3164
304k
                                               DeclaratorDecl *OldD) {
3165
  // The only case where we need to update the DeclContext is when
3166
  // redeclaration lookup for a qualified name finds a declaration
3167
  // in an inline namespace within the context named by the qualifier:
3168
  //
3169
  //   inline namespace N { int f(); }
3170
  //   int ::f(); // Sema DC needs adjusting from :: to N::.
3171
  //
3172
  // For unqualified declarations, the semantic context *can* change
3173
  // along the redeclaration chain (for local extern declarations,
3174
  // extern "C" declarations, and friend declarations in particular).
3175
304k
  if (!NewD->getQualifier())
3176
90.7k
    return;
3177
3178
  // NewD is probably already in the right context.
3179
214k
  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3180
214k
  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3181
214k
  if (NamedDC->Equals(SemaDC))
3182
214k
    return;
3183
3184
21
  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3185
21
          NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3186
21
         "unexpected context for redeclaration");
3187
3188
21
  auto *LexDC = NewD->getLexicalDeclContext();
3189
42
  auto FixSemaDC = [=](NamedDecl *D) {
3190
42
    if (!D)
3191
21
      return;
3192
21
    D->setDeclContext(SemaDC);
3193
21
    D->setLexicalDeclContext(LexDC);
3194
21
  };
3195
3196
21
  FixSemaDC(NewD);
3197
21
  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3198
15
    FixSemaDC(FD->getDescribedFunctionTemplate());
3199
6
  else if (auto *VD = dyn_cast<VarDecl>(NewD))
3200
6
    FixSemaDC(VD->getDescribedVarTemplate());
3201
21
}
3202
3203
/// MergeFunctionDecl - We just parsed a function 'New' from
3204
/// declarator D which has the same name and scope as a previous
3205
/// declaration 'Old'.  Figure out how to resolve this situation,
3206
/// merging decls or emitting diagnostics as appropriate.
3207
///
3208
/// In C++, New and Old must be declarations that are not
3209
/// overloaded. Use IsOverload to determine whether New and Old are
3210
/// overloaded, and to select the Old declaration that New should be
3211
/// merged with.
3212
///
3213
/// Returns true if there was an error, false otherwise.
3214
bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3215
245k
                             Scope *S, bool MergeTypeWithOld) {
3216
  // Verify the old decl was also a function.
3217
245k
  FunctionDecl *Old = OldD->getAsFunction();
3218
245k
  if (!Old) {
3219
73
    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3220
39
      if (New->getFriendObjectKind()) {
3221
11
        Diag(New->getLocation(), diag::err_using_decl_friend);
3222
11
        Diag(Shadow->getTargetDecl()->getLocation(),
3223
11
             diag::note_using_decl_target);
3224
11
        Diag(Shadow->getUsingDecl()->getLocation(),
3225
11
             diag::note_using_decl) << 0;
3226
11
        return true;
3227
11
      }
3228
3229
      // Check whether the two declarations might declare the same function.
3230
28
      if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3231
16
        return true;
3232
12
      OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3233
34
    } else {
3234
34
      Diag(New->getLocation(), diag::err_redefinition_different_kind)
3235
34
        << New->getDeclName();
3236
34
      notePreviousDefinition(OldD, New->getLocation());
3237
34
      return true;
3238
34
    }
3239
245k
  }
3240
3241
  // If the old declaration was found in an inline namespace and the new
3242
  // declaration was qualified, update the DeclContext to match.
3243
245k
  adjustDeclContextForDeclaratorDecl(New, Old);
3244
3245
  // If the old declaration is invalid, just give up here.
3246
245k
  if (Old->isInvalidDecl())
3247
26
    return true;
3248
3249
  // Disallow redeclaration of some builtins.
3250
245k
  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3251
11
    Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3252
11
    Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3253
11
        << Old << Old->getType();
3254
11
    return true;
3255
11
  }
3256
3257
245k
  diag::kind PrevDiag;
3258
245k
  SourceLocation OldLocation;
3259
245k
  std::tie(PrevDiag, OldLocation) =
3260
245k
      getNoteDiagForInvalidRedeclaration(Old, New);
3261
3262
  // Don't complain about this if we're in GNU89 mode and the old function
3263
  // is an extern inline function.
3264
  // Don't complain about specializations. They are not supposed to have
3265
  // storage classes.
3266
245k
  if (!isa<CXXMethodDecl>(New) && 
!isa<CXXMethodDecl>(Old)87.9k
&&
3267
87.9k
      New->getStorageClass() == SC_Static &&
3268
3.83k
      Old->hasExternalFormalLinkage() &&
3269
193
      !New->getTemplateSpecializationInfo() &&
3270
192
      !canRedefineFunction(Old, getLangOpts())) {
3271
188
    if (getLangOpts().MicrosoftExt) {
3272
182
      Diag(New->getLocation(), diag::ext_static_non_static) << New;
3273
182
      Diag(OldLocation, PrevDiag);
3274
6
    } else {
3275
6
      Diag(New->getLocation(), diag::err_static_non_static) << New;
3276
6
      Diag(OldLocation, PrevDiag);
3277
6
      return true;
3278
6
    }
3279
245k
  }
3280
3281
245k
  if (New->hasAttr<InternalLinkageAttr>() &&
3282
1
      !Old->hasAttr<InternalLinkageAttr>()) {
3283
1
    Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3284
1
        << New->getDeclName();
3285
1
    notePreviousDefinition(Old, New->getLocation());
3286
1
    New->dropAttr<InternalLinkageAttr>();
3287
1
  }
3288
3289
245k
  if (CheckRedeclarationModuleOwnership(New, Old))
3290
13
    return true;
3291
3292
245k
  if (!getLangOpts().CPlusPlus) {
3293
22.8k
    bool OldOvl = Old->hasAttr<OverloadableAttr>();
3294
22.8k
    if (OldOvl != New->hasAttr<OverloadableAttr>() && 
!Old->isImplicit()17
) {
3295
14
      Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3296
14
        << New << OldOvl;
3297
3298
      // Try our best to find a decl that actually has the overloadable
3299
      // attribute for the note. In most cases (e.g. programs with only one
3300
      // broken declaration/definition), this won't matter.
3301
      //
3302
      // FIXME: We could do this if we juggled some extra state in
3303
      // OverloadableAttr, rather than just removing it.
3304
14
      const Decl *DiagOld = Old;
3305
14
      if (OldOvl) {
3306
14
        auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3307
14
          const auto *A = D->getAttr<OverloadableAttr>();
3308
14
          return A && !A->isImplicit();
3309
14
        });
3310
        // If we've implicitly added *all* of the overloadable attrs to this
3311
        // chain, emitting a "previous redecl" note is pointless.
3312
9
        DiagOld = OldIter == Old->redecls_end() ? 
nullptr2
: *OldIter;
3313
11
      }
3314
3315
14
      if (DiagOld)
3316
12
        Diag(DiagOld->getLocation(),
3317
12
             diag::note_attribute_overloadable_prev_overload)
3318
12
          << OldOvl;
3319
3320
14
      if (OldOvl)
3321
11
        New->addAttr(OverloadableAttr::CreateImplicit(Context));
3322
3
      else
3323
3
        New->dropAttr<OverloadableAttr>();
3324
14
    }
3325
22.8k
  }
3326
3327
  // If a function is first declared with a calling convention, but is later
3328
  // declared or defined without one, all following decls assume the calling
3329
  // convention of the first.
3330
  //
3331
  // It's OK if a function is first declared without a calling convention,
3332
  // but is later declared or defined with the default calling convention.
3333
  //
3334
  // To test if either decl has an explicit calling convention, we look for
3335
  // AttributedType sugar nodes on the type as written.  If they are missing or
3336
  // were canonicalized away, we assume the calling convention was implicit.
3337
  //
3338
  // Note also that we DO NOT return at this point, because we still have
3339
  // other tests to run.
3340
245k
  QualType OldQType = Context.getCanonicalType(Old->getType());
3341
245k
  QualType NewQType = Context.getCanonicalType(New->getType());
3342
245k
  const FunctionType *OldType = cast<FunctionType>(OldQType);
3343
245k
  const FunctionType *NewType = cast<FunctionType>(NewQType);
3344
245k
  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3345
245k
  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3346
245k
  bool RequiresAdjustment = false;
3347
3348
245k
  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3349
895
    FunctionDecl *First = Old->getFirstDecl();
3350
895
    const FunctionType *FT =
3351
895
        First->getType().getCanonicalType()->castAs<FunctionType>();
3352
895
    FunctionType::ExtInfo FI = FT->getExtInfo();
3353
895
    bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3354
895
    if (!NewCCExplicit) {
3355
      // Inherit the CC from the previous declaration if it was specified
3356
      // there but not here.
3357
810
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3358
810
      RequiresAdjustment = true;
3359
85
    } else if (Old->getBuiltinID()) {
3360
      // Builtin attribute isn't propagated to the new one yet at this point,
3361
      // so we check if the old one is a builtin.
3362
3363
      // Calling Conventions on a Builtin aren't really useful and setting a
3364
      // default calling convention and cdecl'ing some builtin redeclarations is
3365
      // common, so warn and ignore the calling convention on the redeclaration.
3366
2
      Diag(New->getLocation(), diag::warn_cconv_unsupported)
3367
2
          << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3368
2
          << (int)CallingConventionIgnoredReason::BuiltinFunction;
3369
2
      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3370
2
      RequiresAdjustment = true;
3371
83
    } else {
3372
      // Calling conventions aren't compatible, so complain.
3373
83
      bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3374
83
      Diag(New->getLocation(), diag::err_cconv_change)
3375
83
        << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3376
83
        << !FirstCCExplicit
3377
39
        << (!FirstCCExplicit ? "" :
3378
44
            FunctionType::getNameForCallConv(FI.getCC()));
3379
3380
      // Put the note on the first decl, since it is the one that matters.
3381
83
      Diag(First->getLocation(), diag::note_previous_declaration);
3382
83
      return true;
3383
83
    }
3384
245k
  }
3385
3386
  // FIXME: diagnose the other way around?
3387
245k
  if (OldTypeInfo.getNoReturn() && 
!NewTypeInfo.getNoReturn()737
) {
3388
103
    NewTypeInfo = NewTypeInfo.withNoReturn(true);
3389
103
    RequiresAdjustment = true;
3390
103
  }
3391
3392
  // Merge regparm attribute.
3393
245k
  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3394
245k
      OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3395
21
    if (NewTypeInfo.getHasRegParm()) {
3396
5
      Diag(New->getLocation(), diag::err_regparm_mismatch)
3397
5
        << NewType->getRegParmType()
3398
5
        << OldType->getRegParmType();
3399
5
      Diag(OldLocation, diag::note_previous_declaration);
3400
5
      return true;
3401
5
    }
3402
3403
16
    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3404
16
    RequiresAdjustment = true;
3405
16
  }
3406
3407
  // Merge ns_returns_retained attribute.
3408
245k
  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3409
2
    if (NewTypeInfo.getProducesResult()) {
3410
1
      Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3411
1
          << "'ns_returns_retained'";
3412
1
      Diag(OldLocation, diag::note_previous_declaration);
3413
1
      return true;
3414
1
    }
3415
3416
1
    NewTypeInfo = NewTypeInfo.withProducesResult(true);
3417
1
    RequiresAdjustment = true;
3418
1
  }
3419
3420
245k
  if (OldTypeInfo.getNoCallerSavedRegs() !=
3421
1
      NewTypeInfo.getNoCallerSavedRegs()) {
3422
1
    if (NewTypeInfo.getNoCallerSavedRegs()) {
3423
1
      AnyX86NoCallerSavedRegistersAttr *Attr =
3424
1
        New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3425
1
      Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3426
1
      Diag(OldLocation, diag::note_previous_declaration);
3427
1
      return true;
3428
1
    }
3429
3430
0
    NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3431
0
    RequiresAdjustment = true;
3432
0
  }
3433
3434
245k
  if (RequiresAdjustment) {
3435
923
    const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3436
923
    AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3437
923
    New->setType(QualType(AdjustedType, 0));
3438
923
    NewQType = Context.getCanonicalType(New->getType());
3439
923
  }
3440
3441
  // If this redeclaration makes the function inline, we may need to add it to
3442
  // UndefinedButUsed.
3443
245k
  if (!Old->isInlined() && 
New->isInlined()200k
&&
3444
71.3k
      !New->hasAttr<GNUInlineAttr>() &&
3445
71.3k
      !getLangOpts().GNUInline &&
3446
71.3k
      Old->isUsed(false) &&
3447
19
      !Old->isDefined() && 
!New->isThisDeclarationADefinition()15
)
3448
15
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3449
15
                                           SourceLocation()));
3450
3451
  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3452
  // about it.
3453
245k
  if (New->hasAttr<GNUInlineAttr>() &&
3454
38
      Old->isInlined() && 
!Old->hasAttr<GNUInlineAttr>()17
) {
3455
1
    UndefinedButUsed.erase(Old->getCanonicalDecl());
3456
1
  }
3457
3458
  // If pass_object_size params don't match up perfectly, this isn't a valid
3459
  // redeclaration.
3460
245k
  if (Old->getNumParams() > 0 && 
Old->getNumParams() == New->getNumParams()201k
&&
3461
201k
      !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3462
6
    Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3463
6
        << New->getDeclName();
3464
6
    Diag(OldLocation, PrevDiag) << Old << Old->getType();
3465
6
    return true;
3466
6
  }
3467
3468
245k
  if (getLangOpts().CPlusPlus) {
3469
    // C++1z [over.load]p2
3470
    //   Certain function declarations cannot be overloaded:
3471
    //     -- Function declarations that differ only in the return type,
3472
    //        the exception specification, or both cannot be overloaded.
3473
3474
    // Check the exception specifications match. This may recompute the type of
3475
    // both Old and New if it resolved exception specifications, so grab the
3476
    // types again after this. Because this updates the type, we do this before
3477
    // any of the other checks below, which may update the "de facto" NewQType
3478
    // but do not necessarily update the type of New.
3479
222k
    if (CheckEquivalentExceptionSpec(Old, New))
3480
46
      return true;
3481
222k
    OldQType = Context.getCanonicalType(Old->getType());
3482
222k
    NewQType = Context.getCanonicalType(New->getType());
3483
3484
    // Go back to the type source info to compare the declared return types,
3485
    // per C++1y [dcl.type.auto]p13:
3486
    //   Redeclarations or specializations of a function or function template
3487
    //   with a declared return type that uses a placeholder type shall also
3488
    //   use that placeholder, not a deduced type.
3489
222k
    QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3490
222k
    QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3491
222k
    if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3492
72
        canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3493
68
                                       OldDeclaredReturnType)) {
3494
68
      QualType ResQT;
3495
68
      if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3496
9
          OldDeclaredReturnType->isObjCObjectPointerType())
3497
        // FIXME: This does the wrong thing for a deduced return type.
3498
9
        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3499
68
      if (ResQT.isNull()) {
3500
60
        if (New->isCXXClassMember() && 
New->isOutOfLine()14
)
3501
11
          Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3502
11
              << New << New->getReturnTypeSourceRange();
3503
49
        else
3504
49
          Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3505
49
              << New->getReturnTypeSourceRange();
3506
60
        Diag(OldLocation, PrevDiag) << Old << Old->getType()
3507
60
                                    << Old->getReturnTypeSourceRange();
3508
60
        return true;
3509
60
      }
3510
8
      else
3511
8
        NewQType = ResQT;
3512
68
    }
3513
3514
222k
    QualType OldReturnType = OldType->getReturnType();
3515
222k
    QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3516
222k
    if (OldReturnType != NewReturnType) {
3517
      // If this function has a deduced return type and has already been
3518
      // defined, copy the deduced value from the old declaration.
3519
33
      AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3520
33
      if (OldAT && 
OldAT->isDeduced()29
) {
3521
21
        New->setType(
3522
21
            SubstAutoType(New->getType(),
3523
8
                          OldAT->isDependentType() ? Context.DependentTy
3524
13
                                                   : OldAT->getDeducedType()));
3525
21
        NewQType = Context.getCanonicalType(
3526
21
            SubstAutoType(NewQType,
3527
8
                          OldAT->isDependentType() ? Context.DependentTy
3528
13
                                                   : OldAT->getDeducedType()));
3529
21
      }
3530
33
    }
3531
3532
222k
    const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3533
222k
    CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3534
222k
    if (OldMethod && 
NewMethod157k
) {
3535
      // Preserve triviality.
3536
157k
      NewMethod->setTrivial(OldMethod->isTrivial());
3537
3538
      // MSVC allows explicit template specialization at class scope:
3539
      // 2 CXXMethodDecls referring to the same function will be injected.
3540
      // We don't want a redeclaration error.
3541
157k
      bool IsClassScopeExplicitSpecialization =
3542
157k
                              OldMethod->isFunctionTemplateSpecialization() &&
3543
702
                              NewMethod->isFunctionTemplateSpecialization();
3544
157k
      bool isFriend = NewMethod->getFriendObjectKind();
3545
3546
157k
      if (!isFriend && 
NewMethod->getLexicalDeclContext()->isRecord()157k
&&
3547
266
          !IsClassScopeExplicitSpecialization) {
3548
        //    -- Member function declarations with the same name and the
3549
        //       same parameter types cannot be overloaded if any of them
3550
        //       is a static member function declaration.
3551
102
        if (OldMethod->isStatic() != NewMethod->isStatic()) {
3552
1
          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3553
1
          Diag(OldLocation, PrevDiag) << Old << Old->getType();
3554
1
          return true;
3555
1
        }
3556
3557
        // C++ [class.mem]p1:
3558
        //   [...] A member shall not be declared twice in the
3559
        //   member-specification, except that a nested class or member
3560
        //   class template can be declared and then later defined.
3561
101
        if (!inTemplateInstantiation()) {
3562
99
          unsigned NewDiag;
3563
99
          if (isa<CXXConstructorDecl>(OldMethod))
3564
3
            NewDiag = diag::err_constructor_redeclared;
3565
96
          else if (isa<CXXDestructorDecl>(NewMethod))
3566
18
            NewDiag = diag::err_destructor_redeclared;
3567
78
          else if (isa<CXXConversionDecl>(NewMethod))
3568
8
            NewDiag = diag::err_conv_function_redeclared;
3569
70
          else
3570
70
            NewDiag = diag::err_member_redeclared;
3571
3572
99
          Diag(New->getLocation(), NewDiag);
3573
2
        } else {
3574
2
          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3575
2
            << New << New->getType();
3576
2
        }
3577
101
        Diag(OldLocation, PrevDiag) << Old << Old->getType();
3578
101
        return true;
3579
3580
      // Complain if this is an explicit declaration of a special
3581
      // member that was initially declared implicitly.
3582
      //
3583
      // As an exception, it's okay to befriend such methods in order
3584
      // to permit the implicit constructor/destructor/operator calls.
3585
157k
      } else if (OldMethod->isImplicit()) {
3586
105
        if (isFriend) {
3587
101
          NewMethod->setImplicit();
3588
4
        } else {
3589
4
          Diag(NewMethod->getLocation(),
3590
4
               diag::err_definition_of_implicitly_declared_member)
3591
4
            << New << getSpecialMember(OldMethod);
3592
4
          return true;
3593
4
        }
3594
157k
      } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && 
!isFriend30
) {
3595
10
        Diag(NewMethod->getLocation(),
3596
10
             diag::err_definition_of_explicitly_defaulted_member)
3597
10
          << getSpecialMember(OldMethod);
3598
10
        return true;
3599
10
      }
3600
222k
    }
3601
3602
    // C++11 [dcl.attr.noreturn]p1:
3603
    //   The first declaration of a function shall specify the noreturn
3604
    //   attribute if any declaration of that function specifies the noreturn
3605
    //   attribute.
3606
222k
    const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3607
222k
    if (NRA && 
!Old->hasAttr<CXX11NoReturnAttr>()2
) {
3608
1
      Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3609
1
      Diag(Old->getFirstDecl()->getLocation(),
3610
1
           diag::note_noreturn_missing_first_decl);
3611
1
    }
3612
3613
    // C++11 [dcl.attr.depend]p2:
3614
    //   The first declaration of a function shall specify the
3615
    //   carries_dependency attribute for its declarator-id if any declaration
3616
    //   of the function specifies the carries_dependency attribute.
3617
222k
    const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3618
222k
    if (CDA && 
!Old->hasAttr<CarriesDependencyAttr>()3
) {
3619
2
      Diag(CDA->getLocation(),
3620
2
           diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3621
2
      Diag(Old->getFirstDecl()->getLocation(),
3622
2
           diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3623
2
    }
3624
3625
    // (C++98 8.3.5p3):
3626
    //   All declarations for a function shall agree exactly in both the
3627
    //   return type and the parameter-type-list.
3628
    // We also want to respect all the extended bits except noreturn.
3629
3630
    // noreturn should now match unless the old type info didn't have it.
3631
222k
    QualType OldQTypeForComparison = OldQType;
3632
222k
    if (!OldTypeInfo.getNoReturn() && 
NewTypeInfo.getNoReturn()222k
) {
3633
0
      auto *OldType = OldQType->castAs<FunctionProtoType>();
3634
0
      const FunctionType *OldTypeForComparison
3635
0
        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3636
0
      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3637
0
      assert(OldQTypeForComparison.isCanonical());
3638
0
    }
3639
3640
222k
    if (haveIncompatibleLanguageLinkages(Old, New)) {
3641
      // As a special case, retain the language linkage from previous
3642
      // declarations of a friend function as an extension.
3643
      //
3644
      // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3645
      // and is useful because there's otherwise no way to specify language
3646
      // linkage within class scope.
3647
      //
3648
      // Check cautiously as the friend object kind isn't yet complete.
3649
38
      if (New->getFriendObjectKind() != Decl::FOK_None) {
3650
2
        Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3651
2
        Diag(OldLocation, PrevDiag);
3652
36
      } else {
3653
36
        Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3654
36
        Diag(OldLocation, PrevDiag);
3655
36
        return true;
3656
36
      }
3657
222k
    }
3658
3659
    // If the function types are compatible, merge the declarations. Ignore the
3660
    // exception specifier because it was already checked above in
3661
    // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3662
    // about incompatible types under -fms-compatibility.
3663
222k
    if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3664
222k
                                                         NewQType))
3665
222k
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3666
3667
    // If the types are imprecise (due to dependent constructs in friends or
3668
    // local extern declarations), it's OK if they differ. We'll check again
3669
    // during instantiation.
3670
28
    if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3671
12
      return false;
3672
3673
    // Fall through for conflicting redeclarations and redefinitions.
3674
28
  }
3675
3676
  // C: Function types need to be compatible, not identical. This handles
3677
  // duplicate function decls like "void f(int); void f(enum X);" properly.
3678
22.8k
  if (!getLangOpts().CPlusPlus &&
3679
22.8k
      Context.typesAreCompatible(OldQType, NewQType)) {
3680
22.6k
    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3681
22.6k
    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3682
22.6k
    const FunctionProtoType *OldProto = nullptr;
3683
22.6k
    if (MergeTypeWithOld && 
isa<FunctionNoProtoType>(NewFuncType)22.6k
&&
3684
529
        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3685
      // The old declaration provided a function prototype, but the
3686
      // new declaration does not. Merge in the prototype.
3687
63
      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3688
63
      SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3689
63
      NewQType =
3690
63
          Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3691
63
                                  OldProto->getExtProtoInfo());
3692
63
      New->setType(NewQType);
3693
63
      New->setHasInheritedPrototype();
3694
3695
      // Synthesize parameters with the same types.
3696
63
      SmallVector<ParmVarDecl*, 16> Params;
3697
29
      for (const auto &ParamType : OldProto->param_types()) {
3698
29
        ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3699
29
                                                 SourceLocation(), nullptr,
3700
29
                                                 ParamType, /*TInfo=*/nullptr,
3701
29
                                                 SC_None, nullptr);
3702
29
        Param->setScopeInfo(0, Params.size());
3703
29
        Param->setImplicit();
3704
29
        Params.push_back(Param);
3705
29
      }
3706
3707
63
      New->setParams(Params);
3708
63
    }
3709
3710
22.6k
    return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3711
22.6k
  }
3712
3713
  // Check if the function types are compatible when pointer size address
3714
  // spaces are ignored.
3715
162
  if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3716
3
    return false;
3717
3718
  // GNU C permits a K&R definition to follow a prototype declaration
3719
  // if the declared types of the parameters in the K&R definition
3720
  // match the types in the prototype declaration, even when the
3721
  // promoted types of the parameters from the K&R definition differ
3722
  // from the types in the prototype. GCC then keeps the types from
3723
  // the prototype.
3724
  //
3725
  // If a variadic prototype is followed by a non-variadic K&R definition,
3726
  // the K&R definition becomes variadic.  This is sort of an edge case, but
3727
  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3728
  // C99 6.9.1p8.
3729
159
  if (!getLangOpts().CPlusPlus &&
3730
143
      Old->hasPrototype() && 
!New->hasPrototype()114
&&
3731
30
      New->getType()->getAs<FunctionProtoType>() &&
3732
7
      Old->getNumParams() == New->getNumParams()) {
3733
6
    SmallVector<QualType, 16> ArgTypes;
3734
6
    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3735
6
    const FunctionProtoType *OldProto
3736
6
      = Old->getType()->getAs<FunctionProtoType>();
3737
6
    const FunctionProtoType *NewProto
3738
6
      = New->getType()->getAs<FunctionProtoType>();
3739
3740
    // Determine whether this is the GNU C extension.
3741
6
    QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3742
6
                                               NewProto->getReturnType());
3743
6
    bool LooseCompatible = !MergedReturn.isNull();
3744
6
    for (unsigned Idx = 0, End = Old->getNumParams();
3745
14
         LooseCompatible && 
Idx != End13
;
++Idx8
) {
3746
8
      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3747
8
      ParmVarDecl *NewParm = New->getParamDecl(Idx);
3748
8
      if (Context.typesAreCompatible(OldParm->getType(),
3749
3
                                     NewProto->getParamType(Idx))) {
3750
3
        ArgTypes.push_back(NewParm->getType());
3751
5
      } else if (Context.typesAreCompatible(OldParm->getType(),
3752
5
                                            NewParm->getType(),
3753
4
                                            /*CompareUnqualified=*/true)) {
3754
4
        GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3755
4
                                           NewProto->getParamType(Idx) };
3756
4
        Warnings.push_back(Warn);
3757
4
        ArgTypes.push_back(NewParm->getType());
3758
4
      } else
3759
1
        LooseCompatible = false;
3760
8
    }
3761
3762
6
    if (LooseCompatible) {
3763
9
      for (unsigned Warn = 0; Warn < Warnings.size(); 
++Warn4
) {
3764
4
        Diag(Warnings[Warn].NewParm->getLocation(),
3765
4
             diag::ext_param_promoted_not_compatible_with_prototype)
3766
4
          << Warnings[Warn].PromotedType
3767
4
          << Warnings[Warn].OldParm->getType();
3768
4
        if (Warnings[Warn].OldParm->getLocation().isValid())
3769
3
          Diag(Warnings[Warn].OldParm->getLocation(),
3770
3
               diag::note_previous_declaration);
3771
4
      }
3772
3773
5
      if (MergeTypeWithOld)
3774
5
        New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3775
5
                                             OldProto->getExtProtoInfo()));
3776
5
      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3777
5
    }
3778
3779
    // Fall through to diagnose conflicting types.
3780
6
  }
3781
3782
  // A function that has already been declared has been redeclared or
3783
  // defined with a different type; show an appropriate diagnostic.
3784
3785
  // If the previous declaration was an implicitly-generated builtin
3786
  // declaration, then at the very least we should use a specialized note.
3787
154
  unsigned BuiltinID;
3788
154
  if (Old->isImplicit() && 
(BuiltinID = Old->getBuiltinID())71
) {
3789
    // If it's actually a library-defined builtin function like 'malloc'
3790
    // or 'printf', just warn about the incompatible redeclaration.
3791
68
    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3792
65
      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3793
65
      Diag(OldLocation, diag::note_previous_builtin_declaration)
3794
65
        << Old << Old->getType();
3795
65
      return false;
3796
65
    }
3797
3798
3
    PrevDiag = diag::note_previous_builtin_declaration;
3799
3
  }
3800
3801
89
  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3802
89
  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3803
89
  return true;
3804
154
}
3805
3806
/// Completes the merge of two function declarations that are
3807
/// known to be compatible.
3808
///
3809
/// This routine handles the merging of attributes and other
3810
/// properties of function declarations from the old declaration to
3811
/// the new declaration, once we know that New is in fact a
3812
/// redeclaration of Old.
3813
///
3814
/// \returns false
3815
bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3816
245k
                                        Scope *S, bool MergeTypeWithOld) {
3817
  // Merge the attributes
3818
245k
  mergeDeclAttributes(New, Old);
3819
3820
  // Merge "pure" flag.
3821
245k
  if (Old->isPure())
3822
14
    New->setPure();
3823
3824
  // Merge "used" flag.
3825
245k
  if (Old->getMostRecentDecl()->isUsed(false))
3826
3.66k
    New->setIsUsed();
3827
3828
  // Merge attributes from the parameters.  These can mismatch with K&R
3829
  // declarations.
3830
245k
  if (New->getNumParams() == Old->getNumParams())
3831
635k
      
for (unsigned i = 0, e = New->getNumParams(); 245k
i != e;
++i390k
) {
3832
390k
        ParmVarDecl *NewParam = New->getParamDecl(i);
3833
390k
        ParmVarDecl *OldParam = Old->getParamDecl(i);
3834
390k
        mergeParamDeclAttributes(NewParam, OldParam, *this);
3835
390k
        mergeParamDeclTypes(NewParam, OldParam, *this);
3836
390k
      }
3837
3838
245k
  if (getLangOpts().CPlusPlus)
3839
222k
    return MergeCXXFunctionDecl(New, Old, S);
3840
3841
  // Merge the function types so the we get the composite types for the return
3842
  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3843
  // was visible.
3844
22.6k
  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3845
22.6k
  if (!Merged.isNull() && 
MergeTypeWithOld22.6k
)
3846
22.6k
    New->setType(Merged);
3847
3848
22.6k
  return false;
3849
22.6k
}
3850
3851
void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3852
188k
                                ObjCMethodDecl *oldMethod) {
3853
  // Merge the attributes, including deprecated/unavailable
3854
188k
  AvailabilityMergeKind MergeKind =
3855
188k
    isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3856
14.5k
      ? AMK_ProtocolImplementation
3857
174k
      : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? 
AMK_Redeclaration4.73k
3858
169k
                                                       : AMK_Override;
3859
3860
188k
  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3861
3862
  // Merge attributes from the parameters.
3863
188k
  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3864
188k
                                       oe = oldMethod->param_end();
3865
188k
  for (ObjCMethodDecl::param_iterator
3866
188k
         ni = newMethod->param_begin(), ne = newMethod->param_end();
3867
306k
       ni != ne && 
oi != oe117k
;
++ni, ++oi117k
)
3868
117k
    mergeParamDeclAttributes(*ni, *oi, *this);
3869
3870
188k
  CheckObjCMethodOverride(newMethod, oldMethod);
3871
188k
}
3872
3873
186
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3874
186
  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3875
3876
186
  S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3877
95
         ? diag::err_redefinition_different_type
3878
91
         : diag::err_redeclaration_different_type)
3879
186
    << New->getDeclName() << New->getType() << Old->getType();
3880
3881
186
  diag::kind PrevDiag;
3882
186
  SourceLocation OldLocation;
3883
186
  std::tie(PrevDiag, OldLocation)
3884
186
    = getNoteDiagForInvalidRedeclaration(Old, New);
3885
186
  S.Diag(OldLocation, PrevDiag);
3886
186
  New->setInvalidDecl();
3887
186
}
3888
3889
/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3890
/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3891
/// emitting diagnostics as appropriate.
3892
///
3893
/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3894
/// to here in AddInitializerToDecl. We can't check them before the initializer
3895
/// is attached.
3896
void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3897
59.2k
                             bool MergeTypeWithOld) {
3898
59.2k
  if (New->isInvalidDecl() || 
Old->isInvalidDecl()59.2k
)
3899
26
    return;
3900
3901
59.2k
  QualType MergedT;
3902
59.2k
  if (getLangOpts().CPlusPlus) {
3903
58.1k
    if (New->getType()->isUndeducedType()) {
3904
      // We don't know what the new type is until the initializer is attached.
3905
22
      return;
3906
58.1k
    } else if (Context.hasSameType(New->getType(), Old->getType())) {
3907
      // These could still be something that needs exception specs checked.
3908
57.8k
      return MergeVarDeclExceptionSpecs(New, Old);
3909
57.8k
    }
3910
    // C++ [basic.link]p10:
3911
    //   [...] the types specified by all declarations referring to a given
3912
    //   object or function shall be identical, except that declarations for an
3913
    //   array object can specify array types that differ by the presence or
3914
    //   absence of a major array bound (8.3.4).
3915
260
    else if (Old->getType()->isArrayType() && 
New->getType()->isArrayType()148
) {
3916
129
      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3917
129
      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3918
3919
      // We are merging a variable declaration New into Old. If it has an array
3920
      // bound, and that bound differs from Old's bound, we should diagnose the
3921
      // mismatch.
3922
129
      if (!NewArray->isIncompleteArrayType() && 
!NewArray->isDependentType()62
) {
3923
122
        for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3924
75
             
PrevVD = PrevVD->getPreviousDecl()73
) {
3925
75
          QualType PrevVDTy = PrevVD->getType();
3926
75
          if (PrevVDTy->isIncompleteArrayType() || 
PrevVDTy->isDependentType()27
)
3927
52
            continue;
3928
3929
23
          if (!Context.hasSameType(New->getType(), PrevVDTy))
3930
2
            return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3931
23
        }
3932
49
      }
3933
3934
127
      if (OldArray->isIncompleteArrayType() && 
NewArray->isArrayType()56
) {
3935
56
        if (Context.hasSameType(OldArray->getElementType(),
3936
56
                                NewArray->getElementType()))
3937
56
          MergedT = New->getType();
3938
56
      }
3939
      // FIXME: Check visibility. New is hidden but has a complete type. If New
3940
      // has no array bound, it should not inherit one from Old, if Old is not
3941
      // visible.
3942
71
      else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3943
67
        if (Context.hasSameType(OldArray->getElementType(),
3944
67
                                NewArray->getElementType()))
3945
66
          MergedT = Old->getType();
3946
67
      }
3947
127
    }
3948
131
    else if (New->getType()->isObjCObjectPointerType() &&
3949
4
               Old->getType()->isObjCObjectPointerType()) {
3950
4
      MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3951
4
                                              Old->getType());
3952
4
    }
3953
1.10k
  } else {
3954
    // C 6.2.7p2:
3955
    //   All declarations that refer to the same object or function shall have
3956
    //   compatible type.
3957
1.10k
    MergedT = Context.mergeTypes(New->getType(), Old->getType());
3958
1.10k
  }
3959
1.36k
  if (MergedT.isNull()) {
3960
    // It's OK if we couldn't merge types if either type is dependent, for a
3961
    // block-scope variable. In other cases (static data members of class
3962
    // templates, variable templates, ...), we require the types to be
3963
    // equivalent.
3964
    // FIXME: The C++ standard doesn't say anything about this.
3965
214
    if ((New->getType()->isDependentType() ||
3966
174
         Old->getType()->isDependentType()) && 
New->isLocalVarDecl()56
) {
3967
      // If the old type was dependent, we can't merge with it, so the new type
3968
      // becomes dependent for now. We'll reproduce the original type when we
3969
      // instantiate the TypeSourceInfo for the variable.
3970
30
      if (!New->getType()->isDependentType() && 
MergeTypeWithOld7
)
3971
1
        New->setType(Context.DependentTy);
3972
30
      return;
3973
30
    }
3974
184
    return diagnoseVarDeclTypeMismatch(*this, New, Old);
3975
184
  }
3976
3977
  // Don't actually update the type on the new declaration if the old
3978
  // declaration was an extern declaration in a different scope.
3979
1.15k
  if (MergeTypeWithOld)
3980
1.09k
    New->setType(MergedT);
3981
1.15k
}
3982
3983
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3984
59.2k
                                  LookupResult &Previous) {
3985
  // C11 6.2.7p4:
3986
  //   For an identifier with internal or external linkage declared
3987
  //   in a scope in which a prior declaration of that identifier is
3988
  //   visible, if the prior declaration specifies internal or
3989
  //   external linkage, the type of the identifier at the later
3990
  //   declaration becomes the composite type.
3991
  //
3992
  // If the variable isn't visible, we do not merge with its type.
3993
59.2k
  if (Previous.isShadowed())
3994
36
    return false;
3995
3996
59.2k
  if (S.getLangOpts().CPlusPlus) {
3997
    // C++11 [dcl.array]p3:
3998
    //   If there is a preceding declaration of the entity in the same
3999
    //   scope in which the bound was specified, an omitted array bound
4000
    //   is taken to be the same as in that earlier declaration.
4001
58.1k
    return NewVD->isPreviousDeclInSameBlockScope() ||
4002
58.0k
           (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4003
57.8k
            !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4004
1.09k
  } else {
4005
    // If the old declaration was function-local, don't merge with its
4006
    // type unless we're in the same function.
4007
1.09k
    return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4008
31
           OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4009
1.09k
  }
4010
59.2k
}
4011
4012
/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4013
/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4014
/// situation, merging decls or emitting diagnostics as appropriate.
4015
///
4016
/// Tentative definition rules (C99 6.9.2p2) are checked by
4017
/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4018
/// definitions here, since the initializer hasn't been attached.
4019
///
4020
59.2k
void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4021
  // If the new decl is already invalid, don't do any other checking.
4022
59.2k
  if (New->isInvalidDecl())
4023
0
    return;
4024
4025
59.2k
  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4026
4
    return;
4027
4028
59.2k
  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4029
4030
  // Verify the old decl was also a variable or variable template.
4031
59.2k
  VarDecl *Old = nullptr;
4032
59.2k
  VarTemplateDecl *OldTemplate = nullptr;
4033
59.2k
  if (Previous.isSingleResult()) {
4034
59.2k
    if (NewTemplate) {
4035
415
      OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4036
411
      Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 
nullptr4
;
4037
4038
415
      if (auto *Shadow =
4039
3
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4040
3
        if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4041
2
          return New->setInvalidDecl();
4042
58.8k
    } else {
4043
58.8k
      Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4044
4045
58.8k
      if (auto *Shadow =
4046
8
              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4047
8
        if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4048
7
          return New->setInvalidDecl();
4049
59.2k
    }
4050
59.2k
  }
4051
59.2k
  if (!Old) {
4052
47
    Diag(New->getLocation(), diag::err_redefinition_different_kind)
4053
47
        << New->getDeclName();
4054
47
    notePreviousDefinition(Previous.getRepresentativeDecl(),
4055
47
                           New->getLocation());
4056
47
    return New->setInvalidDecl();
4057
47
  }
4058
4059
  // If the old declaration was found in an inline namespace and the new
4060
  // declaration was qualified, update the DeclContext to match.
4061
59.1k
  adjustDeclContextForDeclaratorDecl(New, Old);
4062
4063
  // Ensure the template parameters are compatible.
4064
59.1k
  if (NewTemplate &&
4065
409
      !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4066
409
                                      OldTemplate->getTemplateParameters(),
4067
409
                                      /*Complain=*/true, TPL_TemplateMatch))
4068
10
    return New->setInvalidDecl();
4069
4070
  // C++ [class.mem]p1:
4071
  //   A member shall not be declared twice in the member-specification [...]
4072
  //
4073
  // Here, we need only consider static data members.
4074
59.1k
  if (Old->isStaticDataMember() && 
!New->isOutOfLine()55.9k
) {
4075
11
    Diag(New->getLocation(), diag::err_duplicate_member)
4076
11
      << New->getIdentifier();
4077
11
    Diag(Old->getLocation(), diag::note_previous_declaration);
4078
11
    New->setInvalidDecl();
4079
11
  }
4080
4081
59.1k
  mergeDeclAttributes(New, Old);
4082
  // Warn if an already-declared variable is made a weak_import in a subsequent
4083
  // declaration
4084
59.1k
  if (New->hasAttr<WeakImportAttr>() &&
4085
15
      Old->getStorageClass() == SC_None &&
4086
3
      !Old->hasAttr<WeakImportAttr>()) {
4087
2
    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4088
2
    notePreviousDefinition(Old, New->getLocation());
4089
    // Remove weak_import attribute on new declaration.
4090
2
    New->dropAttr<WeakImportAttr>();
4091
2
  }
4092
4093
59.1k
  if (New->hasAttr<InternalLinkageAttr>() &&
4094
5
      !Old->hasAttr<InternalLinkageAttr>()) {
4095
2
    Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4096
2
        << New->getDeclName();
4097
2
    notePreviousDefinition(Old, New->getLocation());
4098
2
    New->dropAttr<InternalLinkageAttr>();
4099
2
  }
4100
4101
  // Merge the types.
4102
59.1k
  VarDecl *MostRecent = Old->getMostRecentDecl();
4103
59.1k
  if (MostRecent != Old) {
4104
101
    MergeVarDeclTypes(New, MostRecent,
4105
101
                      mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4106
101
    if (New->isInvalidDecl())
4107
6
      return;
4108
59.1k
  }
4109
4110
59.1k
  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4111
59.1k
  if (New->isInvalidDecl())
4112
197
    return;
4113
4114
58.9k
  diag::kind PrevDiag;
4115
58.9k
  SourceLocation OldLocation;
4116
58.9k
  std::tie(PrevDiag, OldLocation) =
4117
58.9k
      getNoteDiagForInvalidRedeclaration(Old, New);
4118
4119
  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4120
58.9k
  if (New->getStorageClass() == SC_Static &&
4121
65
      !New->isStaticDataMember() &&
4122
62
      Old->hasExternalFormalLinkage()) {
4123
16
    if (getLangOpts().MicrosoftExt) {
4124
3
      Diag(New->getLocation(), diag::ext_static_non_static)
4125
3
          << New->getDeclName();
4126
3
      Diag(OldLocation, PrevDiag);
4127
13
    } else {
4128
13
      Diag(New->getLocation(), diag::err_static_non_static)
4129
13
          << New->getDeclName();
4130
13
      Diag(OldLocation, PrevDiag);
4131
13
      return New->setInvalidDecl();
4132
13
    }
4133
58.9k
  }
4134
  // C99 6.2.2p4:
4135
  //   For an identifier declared with the storage-class specifier
4136
  //   extern in a scope in which a prior declaration of that
4137
  //   identifier is visible,23) if the prior declaration specifies
4138
  //   internal or external linkage, the linkage of the identifier at
4139
  //   the later declaration is the same as the linkage specified at
4140
  //   the prior declaration. If no prior declaration is visible, or
4141
  //   if the prior declaration specifies no linkage, then the
4142
  //   identifier has external linkage.
4143
58.9k
  if (New->hasExternalStorage() && 
Old->hasLinkage()1.90k
)
4144
1.90k
    /* Okay */;
4145
57.0k
  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4146
56.9k
           !New->isStaticDataMember() &&
4147
1.11k
           Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4148
4
    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4149
4
    Diag(OldLocation, PrevDiag);
4150
4
    return New->setInvalidDecl();
4151
4
  }
4152
4153
  // Check if extern is followed by non-extern and vice-versa.
4154
58.9k
  if (New->hasExternalStorage() &&
4155
1.90k
      !Old->hasLinkage() && 
Old->isLocalVarDeclOrParm()5
) {
4156
5
    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4157
5
    Diag(OldLocation, PrevDiag);
4158
5
    return New->setInvalidDecl();
4159
5
  }
4160
58.9k
  if (Old->hasLinkage() && 
New->isLocalVarDeclOrParm()58.8k
&&
4161
210
      !New->hasExternalStorage()) {
4162
4
    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4163
4
    Diag(OldLocation, PrevDiag);
4164
4
    return New->setInvalidDecl();
4165
4
  }
4166
4167
58.9k
  if (CheckRedeclarationModuleOwnership(New, Old))
4168
19
    return;
4169
4170
  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4171
4172
  // FIXME: The test for external storage here seems wrong? We still
4173
  // need to check for mismatches.
4174
58.9k
  if (!New->hasExternalStorage() && 
!New->isFileVarDecl()57.0k
&&
4175
      // Don't complain about out-of-line definitions of static members.
4176
70
      !(Old->getLexicalDeclContext()->isRecord() &&
4177
70
        
!New->getLexicalDeclContext()->isRecord()0
)) {
4178
70
    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4179
70
    Diag(OldLocation, PrevDiag);
4180
70
    return New->setInvalidDecl();
4181
70
  }
4182
4183
58.8k
  if (New->isInline() && 
!Old->getMostRecentDecl()->isInline()978
) {
4184
292
    if (VarDecl *Def = Old->getDefinition()) {
4185
      // C++1z [dcl.fcn.spec]p4:
4186
      //   If the definition of a variable appears in a translation unit before
4187
      //   its first declaration as inline, the program is ill-formed.
4188
0
      Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4189
0
      Diag(Def->getLocation(), diag::note_previous_definition);
4190
0
    }
4191
292
  }
4192
4193
  // If this redeclaration makes the variable inline, we may need to add it to
4194
  // UndefinedButUsed.
4195
58.8k
  if (!Old->isInline() && 
New->isInline()58.1k
&&
Old->isUsed(false)292
&&
4196
0
      !Old->getDefinition() && !New->isThisDeclarationADefinition())
4197
0
    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4198
0
                                           SourceLocation()));
4199
4200
58.8k
  if (New->getTLSKind() != Old->getTLSKind()) {
4201
25
    if (!Old->getTLSKind()) {
4202
11
      Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4203
11
      Diag(OldLocation, PrevDiag);
4204
14
    } else if (!New->getTLSKind()) {
4205
10
      Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4206
10
      Diag(OldLocation, PrevDiag);
4207
4
    } else {
4208
      // Do not allow redeclaration to change the variable between requiring
4209
      // static and dynamic initialization.
4210
      // FIXME: GCC allows this, but uses the TLS keyword on the first
4211
      // declaration to determine the kind. Do we need to be compatible here?
4212
4
      Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4213
4
        << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4214
4
      Diag(OldLocation, PrevDiag);
4215
4
    }
4216
25
  }
4217
4218
  // C++ doesn't have tentative definitions, so go right ahead and check here.
4219
58.8k
  if (getLangOpts().CPlusPlus &&
4220
57.8k
      New->isThisDeclarationADefinition() == VarDecl::Definition) {
4221
55.3k
    if (Old->isStaticDataMember() && 
Old->getCanonicalDecl()->isInline()54.7k
&&
4222
12
        Old->getCanonicalDecl()->isConstexpr()) {
4223
      // This definition won't be a definition any more once it's been merged.
4224
8
      Diag(New->getLocation(),
4225
8
           diag::warn_deprecated_redundant_constexpr_static_def);
4226
55.3k
    } else if (VarDecl *Def = Old->getDefinition()) {
4227
42
      if (checkVarDeclRedefinition(Def, New))
4228
33
        return;
4229
58.8k
    }
4230
55.3k
  }
4231
4232
58.8k
  if (haveIncompatibleLanguageLinkages(Old, New)) {
4233
3
    Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4234
3
    Diag(OldLocation, PrevDiag);
4235
3
    New->setInvalidDecl();
4236
3
    return;
4237
3
  }
4238
4239
  // Merge "used" flag.
4240
58.8k
  if (Old->getMostRecentDecl()->isUsed(false))
4241
541
    New->setIsUsed();
4242
4243
  // Keep a chain of previous declarations.
4244
58.8k
  New->setPreviousDecl(Old);
4245
58.8k
  if (NewTemplate)
4246
375
    NewTemplate->setPreviousDecl(OldTemplate);
4247
4248
  // Inherit access appropriately.
4249
58.8k
  New->setAccess(Old->getAccess());
4250
58.8k
  if (NewTemplate)
4251
375
    NewTemplate->setAccess(New->getAccess());
4252
4253
58.8k
  if (Old->isInline())
4254
694
    New->setImplicitlyInline();
4255
58.8k
}
4256
4257
318
void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4258
318
  SourceManager &SrcMgr = getSourceManager();
4259
318
  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4260
318
  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4261
318
  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4262
318
  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4263
318
  auto &HSI = PP.getHeaderSearchInfo();
4264
318
  StringRef HdrFilename =
4265
318
      SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4266
4267
318
  auto noteFromModuleOrInclude = [&](Module *Mod,
4268
16
                                     SourceLocation IncLoc) -> bool {
4269
    // Redefinition errors with modules are common with non modular mapped
4270
    // headers, example: a non-modular header H in module A that also gets
4271
    // included directly in a TU. Pointing twice to the same header/definition
4272
    // is confusing, try to get better diagnostics when modules is on.
4273
16
    if (IncLoc.isValid()) {
4274
8
      if (Mod) {
4275
3
        Diag(IncLoc, diag::note_redefinition_modules_same_file)
4276
3
            << HdrFilename.str() << Mod->getFullModuleName();
4277
3
        if (!Mod->DefinitionLoc.isInvalid())
4278
1
          Diag(Mod->DefinitionLoc, diag::note_defined_here)
4279
1
              << Mod->getFullModuleName();
4280
5
      } else {
4281
5
        Diag(IncLoc, diag::note_redefinition_include_same_file)
4282
5
            << HdrFilename.str();
4283
5
      }
4284
8
      return true;
4285
8
    }
4286
4287
8
    return false;
4288
8
  };
4289
4290
  // Is it the same file and same offset? Provide more information on why
4291
  // this leads to a redefinition error.
4292
318
  if (FNew == FOld && 
FNewDecLoc.second == FOldDecLoc.second304
) {
4293
8
    SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4294
8
    SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4295
8
    bool EmittedDiag =
4296
8
        noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4297
8
    EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4298
4299
    // If the header has no guards, emit a note suggesting one.
4300
8
    if (FOld && 
!HSI.isFileMultipleIncludeGuarded(FOld)5
)
4301
4
      Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4302
4303
8
    if (EmittedDiag)
4304
5
      return;
4305
313
  }
4306
4307
  // Redefinition coming from different files or couldn't do better above.
4308
313
  if (Old->getLocation().isValid())
4309
308
    Diag(Old->getLocation(), diag::note_previous_definition);
4310
313
}
4311
4312
/// We've just determined that \p Old and \p New both appear to be definitions
4313
/// of the same variable. Either diagnose or fix the problem.
4314
59
bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4315
59
  if (!hasVisibleDefinition(Old) &&
4316
10
      (New->getFormalLinkage() == InternalLinkage ||
4317
10
       New->isInline() ||
4318
10
       New->getDescribedVarTemplate() ||
4319
8
       New->getNumTemplateParameterLists() ||
4320
9
       
New->getDeclContext()->isDependentContext()1
)) {
4321
    // The previous definition is hidden, and multiple definitions are
4322
    // permitted (in separate TUs). Demote this to a declaration.
4323
9
    New->demoteThisDefinitionToDeclaration();
4324
4325
    // Make the canonical definition visible.
4326
9
    if (auto *OldTD = Old->getDescribedVarTemplate())
4327
2
      makeMergedDefinitionVisible(OldTD);
4328
9
    makeMergedDefinitionVisible(Old);
4329
9
    return false;
4330
50
  } else {
4331
50
    Diag(New->getLocation(), diag::err_redefinition) << New;
4332
50
    notePreviousDefinition(Old, New->getLocation());
4333
50
    New->setInvalidDecl();
4334
50
    return true;
4335
50
  }
4336
59
}
4337
4338
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4339
/// no declarator (e.g. "struct foo;") is parsed.
4340
Decl *
4341
Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4342
1.01M
                                 RecordDecl *&AnonRecord) {
4343
1.01M
  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4344
1.01M
                                    AnonRecord);
4345
1.01M
}
4346
4347
// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4348
// disambiguate entities defined in different scopes.
4349
// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4350
// compatibility.
4351
// We will pick our mangling number depending on which version of MSVC is being
4352
// targeted.
4353
34.0k
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4354
34.0k
  return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4355
148
             ? S->getMSCurManglingNumber()
4356
33.9k
             : S->getMSLastManglingNumber();
4357
34.0k
}
4358
4359
2.44M
void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4360
2.44M
  if (!Context.getLangOpts().CPlusPlus)
4361
1.38M
    return;
4362
4363
1.06M
  if (isa<CXXRecordDecl>(Tag->getParent())) {
4364
    // If this tag is the direct child of a class, number it if
4365
    // it is anonymous.
4366
57.5k
    if (!Tag->getName().empty() || 
Tag->getTypedefNameForAnonDecl()16.6k
)
4367
41.0k
      return;
4368
16.5k
    MangleNumberingContext &MCtx =
4369
16.5k
        Context.getManglingNumberContext(Tag->getParent());
4370
16.5k
    Context.setManglingNumber(
4371
16.5k
        Tag, MCtx.getManglingNumber(
4372
16.5k
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4373
16.5k
    return;
4374
16.5k
  }
4375
4376
  // If this tag isn't a direct child of a class, number it if it is local.
4377
1.00M
  MangleNumberingContext *MCtx;
4378
1.00M
  Decl *ManglingContextDecl;
4379
1.00M
  std::tie(MCtx, ManglingContextDecl) =
4380
1.00M
      getCurrentMangleNumberContext(Tag->getDeclContext());
4381
1.00M
  if (MCtx) {
4382
13.2k
    Context.setManglingNumber(
4383
13.2k
        Tag, MCtx->getManglingNumber(
4384
13.2k
                 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4385
13.2k
  }
4386
1.00M
}
4387
4388
namespace {
4389
struct NonCLikeKind {
4390
  enum {
4391
    None,
4392
    BaseClass,
4393
    DefaultMemberInit,
4394
    Lambda,
4395
    Friend,
4396
    OtherMember,
4397
    Invalid,
4398
  } Kind = None;
4399
  SourceRange Range;
4400
4401
202k
  explicit operator bool() { return Kind != None; }
4402
};
4403
}
4404
4405
/// Determine whether a class is C-like, according to the rules of C++
4406
/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4407
32.3k
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4408
32.3k
  if (RD->isInvalidDecl())
4409
0
    return {NonCLikeKind::Invalid, {}};
4410
4411
  // C++ [dcl.typedef]p9: [P1766R1]
4412
  //   An unnamed class with a typedef name for linkage purposes shall not
4413
  //
4414
  //    -- have any base classes
4415
32.3k
  if (RD->getNumBases())
4416
4
    return {NonCLikeKind::BaseClass,
4417
4
            SourceRange(RD->bases_begin()->getBeginLoc(),
4418
4
                        RD->bases_end()[-1].getEndLoc())};
4419
32.3k
  bool Invalid = false;
4420
127k
  for (Decl *D : RD->decls()) {
4421
    // Don't complain about things we already diagnosed.
4422
127k
    if (D->isInvalidDecl()) {
4423
12
      Invalid = true;
4424
12
      continue;
4425
12
    }
4426
4427
    //  -- have any [...] default member initializers
4428
127k
    if (auto *FD = dyn_cast<FieldDecl>(D)) {
4429
126k
      if (FD->hasInClassInitializer()) {
4430
4
        auto *Init = FD->getInClassInitializer();
4431
4
        return {NonCLikeKind::DefaultMemberInit,
4432
4
                Init ? Init->getSourceRange() : 
D->getSourceRange()0
};
4433
4
      }
4434
126k
      continue;
4435
126k
    }
4436
4437
    // FIXME: We don't allow friend declarations. This violates the wording of
4438
    // P1766, but not the intent.
4439
656
    if (isa<FriendDecl>(D))
4440
8
      return {NonCLikeKind::Friend, D->getSourceRange()};
4441
4442
    //  -- declare any members other than non-static data members, member
4443
    //     enumerations, or member classes,
4444
648
    if (isa<StaticAssertDecl>(D) || 
isa<IndirectFieldDecl>(D)636
||
4445
604
        isa<EnumDecl>(D))
4446
57
      continue;
4447
591
    auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4448
591
    if (!MemberRD) {
4449
110
      if (D->isImplicit())
4450
58
        continue;
4451
52
      return {NonCLikeKind::OtherMember, D->getSourceRange()};
4452
52
    }
4453
4454
    //  -- contain a lambda-expression,
4455
481
    if (MemberRD->isLambda())
4456
3
      return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4457
4458
    //  and all member classes shall also satisfy these requirements
4459
    //  (recursively).
4460
478
    if (MemberRD->isThisDeclarationADefinition()) {
4461
447
      if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4462
4
        return Kind;
4463
447
    }
4464
478
  }
4465
4466
32.2k
  return {Invalid ? 
NonCLikeKind::Invalid12
:
NonCLikeKind::None32.2k
, {}};
4467
32.3k
}
4468
4469
void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4470
764k
                                        TypedefNameDecl *NewTD) {
4471
764k
  if (TagFromDeclSpec->isInvalidDecl())
4472
8
    return;
4473
4474
  // Do nothing if the tag already has a name for linkage purposes.
4475
764k
  if (TagFromDeclSpec->hasNameForLinkage())
4476
561k
    return;
4477
4478
  // A well-formed anonymous tag must always be a TUK_Definition.
4479
202k
  assert(TagFromDeclSpec->isThisDeclarationADefinition());
4480
4481
  // The type must match the tag exactly;  no qualifiers allowed.
4482
202k
  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4483
690
                           Context.getTagDeclType(TagFromDeclSpec))) {
4484
690
    if (getLangOpts().CPlusPlus)
4485
155
      Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4486
690
    return;
4487
690
  }
4488
4489
  // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4490
  //   An unnamed class with a typedef name for linkage purposes shall [be
4491
  //   C-like].
4492
  //
4493
  // FIXME: Also diagnose if we've already computed the linkage. That ideally
4494
  // shouldn't happen, but there are constructs that the language rule doesn't
4495
  // disallow for which we can't reasonably avoid computing linkage early.
4496
201k
  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4497
31.9k
  NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4498
170k
                             : NonCLikeKind();
4499
201k
  bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4500
201k
  if (NonCLike || 
ChangesLinkage201k
) {
4501
90
    if (NonCLike.Kind == NonCLikeKind::Invalid)
4502
12
      return;
4503
4504
78
    unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4505
78
    if (ChangesLinkage) {
4506
      // If the linkage changes, we can't accept this as an extension.
4507
12
      if (NonCLike.Kind == NonCLikeKind::None)
4508
7
        DiagID = diag::err_typedef_changes_linkage;
4509
5
      else
4510
5
        DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4511
12
    }
4512
4513
78
    SourceLocation FixitLoc =
4514
78
        getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4515
78
    llvm::SmallString<40> TextToInsert;
4516
78
    TextToInsert += ' ';
4517
78
    TextToInsert += NewTD->getIdentifier()->getName();
4518
4519
78
    Diag(FixitLoc, DiagID)
4520
78
      << isa<TypeAliasDecl>(NewTD)
4521
78
      << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4522
78
    if (NonCLike.Kind != NonCLikeKind::None) {
4523
71
      Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4524
71
        << NonCLike.Kind - 1 << NonCLike.Range;
4525
71
    }
4526
78
    Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4527
78
      << NewTD << isa<TypeAliasDecl>(NewTD);
4528
4529
78
    if (ChangesLinkage)
4530
12
      return;
4531
201k
  }
4532
4533
  // Otherwise, set this as the anon-decl typedef for the tag.
4534
201k
  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4535
201k
}
4536
4537
98
static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4538
98
  switch (T) {
4539
18
  case DeclSpec::TST_class:
4540
18
    return 0;
4541
38
  case DeclSpec::TST_struct:
4542
38
    return 1;
4543
0
  case DeclSpec::TST_interface:
4544
0
    return 2;
4545
22
  case DeclSpec::TST_union:
4546
22
    return 3;
4547
20
  case DeclSpec::TST_enum:
4548
20
    return 4;
4549
0
  default:
4550
0
    llvm_unreachable("unexpected type specifier");
4551
98
  }
4552
98
}
4553
4554
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4555
/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4556
/// parameters to cope with template friend declarations.
4557
Decl *
4558
Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4559
                                 MultiTemplateParamsArg TemplateParams,
4560
                                 bool IsExplicitInstantiation,
4561
1.50M
                                 RecordDecl *&AnonRecord) {
4562
1.50M
  Decl *TagD = nullptr;
4563
1.50M
  TagDecl *Tag = nullptr;
4564
1.50M
  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4565
1.35M
      DS.getTypeSpecType() == DeclSpec::TST_struct ||
4566
618k
      DS.getTypeSpecType() == DeclSpec::TST_interface ||
4567
618k
      DS.getTypeSpecType() == DeclSpec::TST_union ||
4568
1.50M
      
DS.getTypeSpecType() == DeclSpec::TST_enum596k
) {
4569
1.50M
    TagD = DS.getRepAsDecl();
4570
4571
1.50M
    if (!TagD) // We probably had an error
4572
165
      return nullptr;
4573
4574
    // Note that the above type specs guarantee that the
4575
    // type rep is a Decl, whereas in many of the others
4576
    // it's a Type.
4577
1.50M
    if (isa<TagDecl>(TagD))
4578
1.25M
      Tag = cast<TagDecl>(TagD);
4579
243k
    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4580
243k
      Tag = CTD->getTemplatedDecl();
4581
1.50M
  }
4582
4583
1.50M
  if (Tag) {
4584
1.50M
    handleTagNumbering(Tag, S);
4585
1.50M
    Tag->setFreeStanding();
4586
1.50M
    if (Tag->isInvalidDecl())
4587
534
      return Tag;
4588
1.50M
  }
4589
4590
1.50M
  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4591
    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4592
    // or incomplete types shall not be restrict-qualified."
4593
17
    if (TypeQuals & DeclSpec::TQ_restrict)
4594
2
      Diag(DS.getRestrictSpecLoc(),
4595
2
           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4596
2
           << DS.getSourceRange();
4597
17
  }
4598
4599
1.50M
  if (DS.isInlineSpecified())
4600
2
    Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4601
2
        << getLangOpts().CPlusPlus17;
4602
4603
1.50M
  if (DS.hasConstexprSpecifier()) {
4604
    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4605
    // and definitions of functions and variables.
4606
    // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4607
    // the declaration of a function or function template
4608
68
    if (Tag)
4609
61
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4610
61
          << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4611
61
          << static_cast<int>(DS.getConstexprSpecifier());
4612
7
    else
4613
7
      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4614
7
          << static_cast<int>(DS.getConstexprSpecifier());
4615
    // Don't emit warnings after this error.
4616
68
    return TagD;
4617
68
  }
4618
4619
1.50M
  DiagnoseFunctionSpecifiers(DS);
4620
4621
1.50M
  if (DS.isFriendSpecified()) {
4622
    // If we're dealing with a decl but not a TagDecl, assume that
4623
    // whatever routines created it handled the friendship aspect.
4624
19.1k
    if (TagD && 
!Tag13.7k
)
4625
11
      return nullptr;
4626
19.1k
    return ActOnFriendTypeDecl(S, DS, TemplateParams);
4627
19.1k
  }
4628
4629
1.48M
  const CXXScopeSpec &SS = DS.getTypeSpecScope();
4630
1.48M
  bool IsExplicitSpecialization =
4631
1.48M
    !TemplateParams.empty() && 
TemplateParams.back()->size() == 0432k
;
4632
1.48M
  if (Tag && 
SS.isNotEmpty()1.48M
&&
!Tag->isCompleteDefinition()1.41k
&&
4633
128
      !IsExplicitInstantiation && 
!IsExplicitSpecialization118
&&
4634
27
      !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4635
    // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4636
    // nested-name-specifier unless it is an explicit instantiation
4637
    // or an explicit specialization.
4638
    //
4639
    // FIXME: We allow class template partial specializations here too, per the
4640
    // obvious intent of DR1819.
4641
    //
4642
    // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4643
15
    Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4644
15
        << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4645
15
    return nullptr;
4646
15
  }
4647
4648
  // Track whether this decl-specifier declares anything.
4649
1.48M
  bool DeclaresAnything = true;
4650
4651
  // Handle anonymous struct definitions.
4652
1.48M
  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4653
895k
    if (!Record->getDeclName() && 
Record->isCompleteDefinition()1.66k
&&
4654
1.66k
        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4655
1.66k
      if (getLangOpts().CPlusPlus ||
4656
1.65k
          
Record->getDeclContext()->isRecord()296
) {
4657
        // If CurContext is a DeclContext that can contain statements,
4658
        // RecursiveASTVisitor won't visit the decls that
4659
        // BuildAnonymousStructOrUnion() will put into CurContext.
4660
        // Also store them here so that they can be part of the
4661
        // DeclStmt that gets created in this case.
4662
        // FIXME: Also return the IndirectFieldDecls created by
4663
        // BuildAnonymousStructOr union, for the same reason?
4664
1.65k
        if (CurContext->isFunctionOrMethod())
4665
36
          AnonRecord = Record;
4666
1.65k
        return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4667
1.65k
                                           Context.getPrintingPolicy());
4668
1.65k
      }
4669
4670
8
      DeclaresAnything = false;
4671
8
    }
4672
895k
  }
4673
4674
  // C11 6.7.2.1p2:
4675
  //   A struct-declaration that does not declare an anonymous structure or
4676
  //   anonymous union shall contain a struct-declarator-list.
4677
  //
4678
  // This rule also existed in C89 and C99; the grammar for struct-declaration
4679
  // did not permit a struct-declaration without a struct-declarator-list.
4680
1.48M
  if (!getLangOpts().CPlusPlus && 
CurContext->isRecord()747k
&&
4681
21
      DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4682
    // Check for Microsoft C extension: anonymous struct/union member.
4683
    // Handle 2 kinds of anonymous struct/union:
4684
    //   struct STRUCT;
4685
    //   union UNION;
4686
    // and
4687
    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4688
    //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4689
21
    if ((Tag && 
Tag->getDeclName()17
) ||
4690
18
        
DS.getTypeSpecType() == DeclSpec::TST_typename7
) {
4691
18
      RecordDecl *Record = nullptr;
4692
18
      if (Tag)
4693
14
        Record = dyn_cast<RecordDecl>(Tag);
4694
4
      else if (const RecordType *RT =
4695
3
                   DS.getRepAsType().get()->getAsStructureType())
4696
3
        Record = RT->getDecl();
4697
1
      else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4698
1
        Record = UT->getDecl();
4699
4700
18
      if (Record && getLangOpts().MicrosoftExt) {
4701
9
        Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4702
9
            << Record->isUnion() << DS.getSourceRange();
4703
9
        return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4704
9
      }
4705
4706
9
      DeclaresAnything = false;
4707
9
    }
4708
21
  }
4709
4710
  // Skip all the checks below if we have a type error.
4711
1.48M
  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4712
1.48M
      (TagD && 
TagD->isInvalidDecl()1.48M
))
4713
171
    return TagD;
4714
4715
1.48M
  if (getLangOpts().CPlusPlus &&
4716
736k
      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4717
736k
    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4718
80.9k
      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4719
1.44k
          !Enum->getIdentifier() && 
!Enum->isInvalidDecl()12
)
4720
12
        DeclaresAnything = false;
4721
4722
1.48M
  if (!DS.isMissingDeclaratorOk()) {
4723
    // Customize diagnostic for a typedef missing a name.
4724
115
    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4725
12
      Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4726
12
          << DS.getSourceRange();
4727
103
    else
4728
103
      DeclaresAnything = false;
4729
115
  }
4730
4731
1.48M
  if (DS.isModulePrivateSpecified() &&
4732
18
      Tag && Tag->getDeclContext()->isFunctionOrMethod())
4733
1
    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4734
1
      << Tag->getTagKind()
4735
1
      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4736
4737
1.48M
  ActOnDocumentableDecl(TagD);
4738
4739
  // C 6.7/2:
4740
  //   A declaration [...] shall declare at least a declarator [...], a tag,
4741
  //   or the members of an enumeration.
4742
  // C++ [dcl.dcl]p3:
4743
  //   [If there are no declarators], and except for the declaration of an
4744
  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4745
  //   names into the program, or shall redeclare a name introduced by a
4746
  //   previous declaration.
4747
1.48M
  if (!DeclaresAnything) {
4748
    // In C, we allow this as a (popular) extension / bug. Don't bother
4749
    // producing further diagnostics for redundant qualifiers after this.
4750
132
    Diag(DS.getBeginLoc(), (IsExplicitInstantiation || 
!TemplateParams.empty()126
)
4751
37
                               ? diag::err_no_declarators
4752
95
                               : diag::ext_no_declarators)
4753
132
        << DS.getSourceRange();
4754
132
    return TagD;
4755
132
  }
4756
4757
  // C++ [dcl.stc]p1:
4758
  //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4759
  //   init-declarator-list of the declaration shall not be empty.
4760
  // C++ [dcl.fct.spec]p1:
4761
  //   If a cv-qualifier appears in a decl-specifier-seq, the
4762
  //   init-declarator-list of the declaration shall not be empty.
4763
  //
4764
  // Spurious qualifiers here appear to be valid in C.
4765
1.48M
  unsigned DiagID = diag::warn_standalone_specifier;
4766
1.48M
  if (getLangOpts().CPlusPlus)
4767
736k
    DiagID = diag::ext_standalone_specifier;
4768
4769
  // Note that a linkage-specification sets a storage class, but
4770
  // 'extern "C" struct foo;' is actually valid and not theoretically
4771
  // useless.
4772
1.48M
  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4773
21
    if (SCS == DeclSpec::SCS_mutable)
4774
      // Since mutable is not a viable storage class specifier in C, there is
4775
      // no reason to treat it as an extension. Instead, diagnose as an error.
4776
1
      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4777
20
    else if (!DS.isExternInLinkageSpec() && 
SCS != DeclSpec::SCS_typedef14
)
4778
2
      Diag(DS.getStorageClassSpecLoc(), DiagID)
4779
2
        << DeclSpec::getSpecifierName(SCS);
4780
21
  }
4781
4782
1.48M
  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4783
0
    Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4784
0
      << DeclSpec::getSpecifierName(TSCS);
4785
1.48M
  if (DS.getTypeQualifiers()) {
4786
4
    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4787
1
      Diag(DS.getConstSpecLoc(), DiagID) << "const";
4788
4
    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4789
0
      Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4790
    // Restrict is covered above.
4791
4
    if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4792
2
      Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4793
4
    if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4794
0
      Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4795
4
  }
4796
4797
  // Warn about ignored type attributes, for example:
4798
  // __attribute__((aligned)) struct A;
4799
  // Attributes should be placed after tag to apply to type declaration.
4800
1.48M
  if (!DS.getAttributes().empty()) {
4801
15
    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4802
15
    if (TypeSpecType == DeclSpec::TST_class ||
4803
13
        TypeSpecType == DeclSpec::TST_struct ||
4804
6
        TypeSpecType == DeclSpec::TST_interface ||
4805
6
        TypeSpecType == DeclSpec::TST_union ||
4806
15
        
TypeSpecType == DeclSpec::TST_enum4
) {
4807
15
      for (const ParsedAttr &AL : DS.getAttributes())
4808
22
        Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4809
22
            << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4810
15
    }
4811
15
  }
4812
4813
1.48M
  return TagD;
4814
1.48M
}
4815
4816
/// We are trying to inject an anonymous member into the given scope;
4817
/// check if there's an existing declaration that can't be overloaded.
4818
///
4819
/// \return true if this is a forbidden redeclaration
4820
static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4821
                                         Scope *S,
4822
                                         DeclContext *Owner,
4823
                                         DeclarationName Name,
4824
                                         SourceLocation NameLoc,
4825
3.03k
                                         bool IsUnion) {
4826
3.03k
  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4827
3.03k
                 Sema::ForVisibleRedeclaration);
4828
3.03k
  if (!SemaRef.LookupName(R, S)) 
return false3.01k
;
4829
4830
  // Pick a representative declaration.
4831
17
  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4832
17
  assert(PrevDecl && "Expected a non-null Decl");
4833
4834
17
  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4835
8
    return false;
4836
4837
9
  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4838
9
    << IsUnion << Name;
4839
9
  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4840
4841
9
  return true;
4842
9
}
4843
4844
/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4845
/// anonymous struct or union AnonRecord into the owning context Owner
4846
/// and scope S. This routine will be invoked just after we realize
4847
/// that an unnamed union or struct is actually an anonymous union or
4848
/// struct, e.g.,
4849
///
4850
/// @code
4851
/// union {
4852
///   int i;
4853
///   float f;
4854
/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4855
///    // f into the surrounding scope.x
4856
/// @endcode
4857
///
4858
/// This routine is recursive, injecting the names of nested anonymous
4859
/// structs/unions into the owning context and scope as well.
4860
static bool
4861
InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4862
                                    RecordDecl *AnonRecord, AccessSpecifier AS,
4863
1.66k
                                    SmallVectorImpl<NamedDecl *> &Chaining) {
4864
1.66k
  bool Invalid = false;
4865
4866
  // Look every FieldDecl and IndirectFieldDecl with a name.
4867
3.90k
  for (auto *D : AnonRecord->decls()) {
4868
3.90k
    if ((isa<FieldDecl>(D) || 
isa<IndirectFieldDecl>(D)931
) &&
4869
3.19k
        cast<NamedDecl>(D)->getDeclName()) {
4870
3.03k
      ValueDecl *VD = cast<ValueDecl>(D);
4871
3.03k
      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4872
3.03k
                                       VD->getLocation(),
4873
9
                                       AnonRecord->isUnion())) {
4874
        // C++ [class.union]p2:
4875
        //   The names of the members of an anonymous union shall be
4876
        //   distinct from the names of any other entity in the
4877
        //   scope in which the anonymous union is declared.
4878
9
        Invalid = true;
4879
3.02k
      } else {
4880
        // C++ [class.union]p2:
4881
        //   For the purpose of name lookup, after the anonymous union
4882
        //   definition, the members of the anonymous union are
4883
        //   considered to have been defined in the scope in which the
4884
        //   anonymous union is declared.
4885
3.02k
        unsigned OldChainingSize = Chaining.size();
4886
3.02k
        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4887
222
          Chaining.append(IF->chain_begin(), IF->chain_end());
4888
2.80k
        else
4889
2.80k
          Chaining.push_back(VD);
4890
4891
3.02k
        assert(Chaining.size() >= 2);
4892
3.02k
        NamedDecl **NamedChain =
4893
3.02k
          new (SemaRef.Context)NamedDecl*[Chaining.size()];
4894
9.33k
        for (unsigned i = 0; i < Chaining.size(); 
i++6.30k
)
4895
6.30k
          NamedChain[i] = Chaining[i];
4896
4897
3.02k
        IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4898
3.02k
            SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4899
3.02k
            VD->getType(), {NamedChain, Chaining.size()});
4900
4901
3.02k
        for (const auto *Attr : VD->attrs())
4902
12
          IndirectField->addAttr(Attr->clone(SemaRef.Context));
4903
4904
3.02k
        IndirectField->setAccess(AS);
4905
3.02k
        IndirectField->setImplicit();
4906
3.02k
        SemaRef.PushOnScopeChains(IndirectField, S);
4907
4908
        // That includes picking up the appropriate access specifier.
4909
3.02k
        if (AS != AS_none) 
IndirectField->setAccess(AS)2.43k
;
4910
4911
3.02k
        Chaining.resize(OldChainingSize);
4912
3.02k
      }
4913
3.03k
    }
4914
3.90k
  }
4915
4916
1.66k
  return Invalid;
4917
1.66k
}
4918
4919
/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4920
/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4921
/// illegal input values are mapped to SC_None.
4922
static StorageClass
4923
2.68M
StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4924
2.68M
  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4925
2.68M
  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4926
2.68M
         "Parser allowed 'typedef' as storage class VarDecl.");
4927
2.68M
  switch (StorageClassSpec) {
4928
1.24M
  case DeclSpec::SCS_unspecified:    return SC_None;
4929
1.23M
  case DeclSpec::SCS_extern:
4930
1.23M
    if (DS.isExternInLinkageSpec())
4931
49.7k
      return SC_None;
4932
1.18M
    return SC_Extern;
4933
195k
  case DeclSpec::SCS_static:         return SC_Static;
4934
39
  case DeclSpec::SCS_auto:           return SC_Auto;
4935
644
  case DeclSpec::SCS_register:       return SC_Register;
4936
58
  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4937
    // Illegal SCSs map to None: error reporting is up to the caller.
4938
4
  case DeclSpec::SCS_mutable:        // Fall through.
4939
4
  case DeclSpec::SCS_typedef:        return SC_None;
4940
0
  }
4941
0
  llvm_unreachable("unknown storage class specifier");
4942
0
}
4943
4944
19
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4945
19
  assert(Record->hasInClassInitializer());
4946
4947
38
  for (const auto *I : Record->decls()) {
4948
38
    const auto *FD = dyn_cast<FieldDecl>(I);
4949
38
    if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4950
4
      FD = IFD->getAnonField();
4951
38
    if (FD && 
FD->hasInClassInitializer()24
)
4952
19
      return FD->getLocation();
4953
38
  }