Coverage Report

Created: 2020-02-25 14:32

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